<?php
/**
 * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

namespace SDXApi\Model;

use Think\Model;

class OrderinfoModel extends Model {
// 	public $pre = C('DB_PREFIX'); 
	protected $tableName = 'order_info';
// 	public function __construct(){
// 	 	 $this->pre=C('DB_PREFIX');
// 	 }

    /**
     * 预计送达时间
     * @param $order_details
     * @return string
     */
	public function get_expected_pickup_time($order_details){
//		dd($order_details);
//	    if($order_details['best_time_start']==0){
//	        if($order_details['is_presell']==1){
//	            $new_best_time = date("Y-m-d",$order_details['best_time'])." 20:30:00";
//	            $order_details['best_time'] = strtotime($new_best_time)-1;
//	            $order_details['best_time_start'] = strtotime(date("Y-m-d",$order_details['best_time'])." 10:00:00");
//	        }else{
//	            $order_details['best_time_start'] = $order_details['best_time_start']-2*3600;
//	        }
//	    }
	    
	    //$today = date("Y-m-d",time());
	    $beginday = date("Y-m-d",$order_details['best_time_start']);
	    
//	    if($today == $beginday){
//	        $datetime = "[{$beginday}]";
//	    }else{
//	        $datetime = "[".$beginday."] ";
//	    }
	    
	    //            自提单时间修改
	    //$best_time_shipping = strtotime(date("Y-m-d", $order_details['best_time']) ." 22:00:00");
//	    if ($order_details['shipping_id'] == 2) {
//	        if(date("H")>21){
//                $begindayShipping = date('Y-m-d', strtotime("+1 day"));
//            }else{
//                $begindayShipping = date('Y-m-d');
//            }
//            //$datetime = " [ {$begindayShipping} ] ";
//            $strBestTimeStart = strtotime(date("Y-m-d") ." 10:00:00");
//            $order_details['best_time'] = strtotime(date("Y-m-d") ." 22:00:00");
//	    }else{
//			$strBestTimeStart = $order_details['best_time_start'];
		//}
	    
	    $expected_pickup_time = "[ ".$beginday." ] ".date("H:i", $order_details['best_time_start']).'-'.date("H:i",$order_details['best_time']);
	    return $expected_pickup_time;
	}
	
    /**
     * 返回891订单数据
     * Created by Jerry
     * @param $startTime
     * @param $endTime
     * @return mixed
     */
    public function get_891_order_info($startTime, $endTime, $pager)
    {
        if (empty($pager['firstpage'])){
            $pager['firstpage']+= 0;
        }

        $sql = "SELECT 
                    o.order_sn,
                    u.user_name,
                    o.order_id,
                    o.add_time,
                    o.pay_time,
                    o.pay_name,
                    o.referer
                FROM
                    sdx_order_info AS o
                        RIGHT JOIN
                    sdx_order_goods AS og ON o.order_id = og.order_id
                        RIGHT JOIN
                    sdx_goods AS g ON og.goods_id = g.goods_id
                        RIGHT JOIN
                    sdx_users AS u ON u.user_id = o.user_id
                WHERE
                    g.sources = 891
                        AND o.add_time < '{$endTime}'
                        AND o.add_time >= '{$startTime}'
                        AND (o.pay_status != 0 AND o.pay_status != 1)
                GROUP BY o.order_sn
                ORDER BY o.add_time DESC
                limit {$pager['firstpage']},10";


        return $this->query($sql);
    }

    /**
     * 返回891订单总数
     * Created by Jerry
     * @param $startTime
     * @param $endTime
     * @return mixed
     */
    public function get_891_order_count($startTime, $endTime)
    {

        $sql = "SELECT 
                    o.order_sn,
                    u.user_name,
                    o.order_id,
                    o.add_time,
                    o.pay_time,
                    o.pay_name,
                    o.referer
                FROM
                    sdx_order_info AS o
                        RIGHT JOIN
                    sdx_order_goods AS og ON o.order_id = og.order_id
                        RIGHT JOIN
                    sdx_goods AS g ON og.goods_id = g.goods_id
                        RIGHT JOIN
                    sdx_users AS u ON u.user_id = o.user_id
                WHERE
                    g.sources = 891
                        AND o.add_time < '{$endTime}'
                        AND o.add_time >= '{$startTime}'
                        AND (o.pay_status != 0 AND o.pay_status != 1)
                GROUP BY o.order_sn
                ORDER BY o.add_time DESC";


        $data = $this->query($sql);
        return count($data);
    }

	/**
	 * 
	 * @param unknown $order_id
	 * @param unknown $action_array
	 * @return unknown $return_res
	 */
	
	public function del_delivery($order_id, $action_array) {
		$model = new Model();
		$return_res = 0;
		
		if (empty ( $order_id ) || empty ( $action_array )) {
			return $return_res;
		}
		
		$query_delivery = 1;
		$query_back = 1;
		if (in_array ( 'delivery', $action_array )) {
			$sql = 'DELETE O, G
     					FROM ' . C('DB_PREFIX'). 'delivery_order AS O, ' .  C('DB_PREFIX') . 'delivery_goods AS G
		                WHERE O.order_id = \'' . $order_id . '\'
		                AND O.delivery_id = G.delivery_id';
			$query_delivery = $model->execute($sql);
		}
		if (in_array ( 'back', $action_array )) {
			$sql = 'DELETE O, G
                FROM ' . C('DB_PREFIX') . 'back_order AS O, ' . C('DB_PREFIX') . 'back_goods AS G
                WHERE O.order_id = \'' . $order_id . '\'
                AND O.back_id = G.back_id';
			$query_back = $model->execute($sql);
		}
		
		if ($query_delivery && $query_back) {
			$return_res = 1;
		}
		
		return $return_res;
	}
	
	
	/**
	 * 获得订单信息
	 *
	 * @access  private
	 * @return  array
	 */
	function flow_order_info() {
	    $order = isset($_SESSION['flow_order']) ? $_SESSION['flow_order'] : array();
	
	    /* 初始化配送和支付方式 */
	    if (!isset($order['shipping_id']) || !isset($order['pay_id'])) {
	        /* 如果还没有设置配送和支付 */
	        if ($_SESSION['user_id'] > 0) {
	            /* 用户已经登录了，则获得上次使用的配送和支付 */
	            $arr = model('Order')->last_shipping_and_payment();
	
	            if (!isset($order['shipping_id'])) {
	                $order['shipping_id'] = $arr['shipping_id'];
	            }
	            if (!isset($order['pay_id'])) {
	                $order['pay_id'] = $arr['pay_id'];
	            }
	        } else {
	            if (!isset($order['shipping_id'])) {
	                $order['shipping_id'] = 0;
	            }
	            if (!isset($order['pay_id'])) {
	                $order['pay_id'] = 0;
	            }
	        }
	    }
	
	    if (!isset($order['pack_id'])) {
	        $order['pack_id'] = 0;  // 初始化包装
	    }
	    if (!isset($order['card_id'])) {
	        $order['card_id'] = 0;  // 初始化贺卡
	    }
	    if (!isset($order['bonus'])) {
	        $order['bonus'] = 0;    // 初始化红包
	    }
	    if (!isset($order['integral'])) {
	        $order['integral'] = 0; // 初始化积分
	    }
	    if (!isset($order['surplus'])) {
	        $order['surplus'] = 0;  // 初始化余额
	    }
	
	    /* 扩展信息 */
	    if (isset($_SESSION['flow_type']) && intval($_SESSION['flow_type']) != CART_GENERAL_GOODS) {
	        $order['extension_code'] = $_SESSION['extension_code'];
	        $order['extension_id'] = $_SESSION['extension_id'];
	    }
	
	    return $order;
	}
	
	/**
	 * @param int $country_id
	 * @param int $province_id
	 * @param int $city_id
	 * @param int $district_id
	 * @param string $address
	 */
	public function get_address_gps($country_id,$province_id,$city_id,$district_id,$address){
		$country = M('region')->where(array('region_id'=>$country_id))->getField('region_name');
		$province = M('region')->where(array('region_id'=>$province_id))->getField('region_name');
		$city = M('region')->where(array('region_id'=>$city_id))->getField('region_name');
		$district = M('region')->where(array('region_id'=>$district_id))->getField('region_name');
		$all_address = str_replace(' ','',$country.$province.$city.$district.$address);
		$gps = address_to_gps_amap($all_address,$city);
		return $gps;
	}
	
	/**
	 * 返回订单中的虚拟商品
	 * @access  public
	 * @param   int   $order_id   订单id值
	 * @param   bool  $shipping   是否已经发货
	 * @return array()
	 */
	public function get_virtual_goods($order_id, $shipping = false) {
		$order_goods = D('order_goods');
		if ($shipping) {
			$sql = 'SELECT goods_id, goods_name, send_number AS num, extension_code FROM ' . C('DB_PREFIX') .
			"order_goods WHERE order_id = '$order_id' AND extension_code > ''";
		} else {
			$sql = 'SELECT goods_id, goods_name, (goods_number - send_number) AS num, extension_code FROM ' . C('DB_PREFIX') .
			"order_goods WHERE order_id = '$order_id' AND is_real = 0 AND (goods_number - send_number) > 0 AND extension_code > '' ";
		}
		$res = $order_goods->execute($sql);
	
		$virtual_goods = array();
		if (is_array($res))
			foreach ($res AS $row) {
				$virtual_goods[$row['extension_code']][] = array('goods_id' => $row['goods_id'], 'goods_name' => $row['goods_name'], 'num' => $row['num']);
			}
	
		return $virtual_goods;
	}
	
	/**
	 *  虚拟商品发货
	 *
	 * @access  public
	 * @param   array  $virtual_goods   虚拟商品数组
	 * @param   string $msg             错误信息
	 * @param   string $order_sn        订单号。
	 * @param   string $process         设定当前流程：split，发货分单流程；other，其他，默认。
	 *
	 * @return bool
	 */
	public function virtual_goods_ship(&$virtual_goods, &$msg, $order_sn, $return_result = false, $process = 'other') {
		$virtual_card = array();
		$res = array();
		foreach ($virtual_goods AS $code => $goods_list) {
			/* 只处理虚拟卡 */
			if ($code == 'virtual_card') {
				foreach ($goods_list as $goods) {
					$shipping_res = $this->virtual_card_shipping($goods, $order_sn, $msg, $process);
					$shipping_statue = $shipping_res['statue'];  
					unset($shipping_res['statue']);
					if ($shipping_statue) {
						if ($return_result) {
							$virtual_card[] = array('goods_id' => $goods['goods_id'], 'goods_name' => $goods['goods_name'], 'info' => $this->virtual_card_result($order_sn, $goods));
						}
					} else {
						$res['status'] = false;
						return $res;
					}
				}
				$res['virtual_card'] = $virtual_card;
			}
		}
		$res['status'] = true;
		$res = array_merge($shipping_res,$res);
		return $res;
	}
	
	/**
	 *  虚拟卡发货
	 *
	 * @access  public
	 * @param   string      $goods      商品详情数组
	 * @param   string      $order_sn   本次操作的订单
	 * @param   string      $msg        返回信息
	 * @param   string      $process    设定当前流程：split，发货分单流程；other，其他，默认。
	 *
	 * @return  boolen
	 */
	public function virtual_card_shipping($goods, $order_sn='', &$msg, $process = 'other') {
		/* 检查有没有缺货 */
		$result = array();
		$virtual_card_obj = D('virtual_card');
		$map = array('goods_id'=>$goods['goods_id'],'is_saled'=>0);
		$num = $virtual_card_obj->where($map)->count();
		
		if ($num < $goods['num']) {
			$msg .= sprintf("虚拟卡%s已缺货", $goods['goods_name']);
			$result['status'] = false;
			return $result;
		}
		/* 取出卡片信息 */
		$arr = $virtual_card_obj->field('card_id, card_sn, card_password, end_date, crc32')->where($map)->limit($goods['num'])->select();
	
		$card_ids = array();
		$cards = array();
	
		foreach ($arr as $virtual_card) {
			$card_info = array();
	
			/* 卡号和密码解密 */
			if ($virtual_card['crc32'] == 0 || $virtual_card['crc32'] == crc32(AUTH_KEY)) {
				$card_info['card_sn'] = decrypt($virtual_card['card_sn']);
				$card_info['card_password'] = decrypt($virtual_card['card_password']);
			} elseif ($virtual_card['crc32'] == crc32(OLD_AUTH_KEY)) {
				$card_info['card_sn'] = decrypt($virtual_card['card_sn'], OLD_AUTH_KEY);
				$card_info['card_password'] = decrypt($virtual_card['card_password'], OLD_AUTH_KEY);
			} else {
				$msg .= 'error key';
				$result['status'] = false;
				return $result;
			}
			$card_info['end_date'] = date(C('date_format'), $virtual_card['end_date']);
			$card_ids[] = $virtual_card['card_id'];
			$cards[] = $card_info;
		}
	
		/* 标记已经取出的卡片 */
		$data = array('is_saled'=>1,'order_sn'=>$order_sn);
		$res = $virtual_card_obj->where(array('card_id'=>array('in',$card_ids)))->setField($data);
		if ($res===false) {
			$msg .=$virtual_card_obj->getDbError();
			$result['status'] = false;
			return $result;
		}
	
		/* 更新库存 */
		D('goods')->where(array('goods_id'=>$goods[goods_id]))->setDec('goods_number',$goods['num']);
	
		if (true) {
			/* 获取订单信息 */
			$order_info = M('order_info');
			$order = $order_info->where(array('order_sn'=>$order_sn))->find();
	
			/* 更新订单信息 */
			$order_goods = D('order_goods');
			$map = array('order_id'=>$order['order_id'],'goods_id'=> $goods['goods_id']);
			if ($process == 'split') {
				$res = $order_goods->where($map)->setInc('send_number',$goods['num']);
			} else {
				$res = $order_goods->where($map)->setField('send_number',$goods['num']);
			}
	
			if ($res===false) {
				$msg .= $order_goods->getDbError();
				$result['status'] = false;
				return $result;
			}
		}
		
		//返回数据
		$result['virtual_card'] = $cards;
		$result['order'] = $order;
		$result['goods'] = $goods;
		$result['gosend_timeods'] =  date('Y-m-d H:i:s');
		$result['shop_name'] = C('shop_name');
		$result['send_date'] = date('Y-m-d');
		$result['sent_date'] = date('Y-m-d');
		
		$result['status'] = true;
		
		return $result;
	}
	
	/**
	 * 取得某订单应该赠送的积分数
	 * @param   array   $order  订单
	 * @return  int     积分数
	 */
	public function integral_to_give($order) {
		/* 判断是否团购 */
		if ($order['extension_code'] == 'group_buy') {
			$group_buy = $this->group_buy_info(intval($order['extension_id']));
	
			return array('custom_points' => $group_buy['gift_integral'], 'rank_points' => $order['goods_amount']);
		} else {
			$sql = "SELECT SUM(og.goods_number * IF(g.give_integral > -1, g.give_integral, og.goods_price)) AS custom_points, SUM(og.goods_number * IF(g.rank_integral > -1, g.rank_integral, og.goods_price)) AS rank_points " .
					"FROM " . C('DB_PREFIX') . "order_goods AS og, " .
					C('DB_PREFIX') . "goods AS g " .
					"WHERE og.goods_id = g.goods_id " .
					"AND og.order_id = '$order[order_id]' " .
					"AND og.goods_id > 0 " .
					"AND og.parent_id = 0 " .
					"AND og.is_gift = 0 AND og.extension_code != 'package_buy'";
			$res = $model = new Model();
			return current($res);
		}
	}
	
	/**
	 * 取得团购活动信息
	 * @param   int     $group_buy_id   团购活动id
	 * @param   int     $current_num    本次购买数量（计算当前价时要加上的数量）
	 * @return  array
	 *                  status          状态：
	 */
	public function group_buy_info($group_buy_id, $current_num = 0) {
		/* 取得团购活动信息 */
		$group_buy_id = intval($group_buy_id);
		$sql = "SELECT *, a.act_id AS group_buy_id, a.act_desc AS group_buy_desc, a.start_time AS start_date, a.end_time AS end_date ,
        ta.sales_count ,ta.act_banner , ta.click_num " .
	        "FROM " . C('DB_PREFIX') .
	        "goods_activity as a LEFT JOIN " . C('DB_PREFIX') . 'touch_goods_activity as ta ON a.act_id = ta.act_id ' .
	        "WHERE a.act_id = '$group_buy_id' " .
	        "AND a.act_type = '" . GAT_GROUP_BUY . "'";
		$model = new Model();
		$res = $model->query($sql);
		$group_buy = current($res);
		
		
	
		/* 如果为空，返回空数组 */
		if (empty($group_buy)) {
			return array();
		}
	
		$ext_info = unserialize($group_buy['ext_info']);
		$group_buy = array_merge($group_buy, $ext_info);
	
		/* 格式化时间 */
		$group_buy['formated_start_date'] = local_date('Y-m-d H:i', $group_buy['start_time']);
		$group_buy['formated_end_date'] = local_date('Y-m-d H:i', $group_buy['end_time']);
	
		/* 格式化保证金 */
		$group_buy['formated_deposit'] = price_format($group_buy['deposit'], false);
	
		/* 处理价格阶梯 */
		$price_ladder = $group_buy['price_ladder'];
		if (!is_array($price_ladder) || empty($price_ladder)) {
			$price_ladder = array(array('amount' => 0, 'price' => 0));
		} else {
			foreach ($price_ladder as $key => $amount_price) {
				$price_ladder[$key]['formated_price'] = price_format($amount_price['price'], false);
			}
		}
		$group_buy['price_ladder'] = $price_ladder;
	
		/* 统计信息 */
		$stat = $this->group_buy_stat($group_buy_id, $group_buy['deposit']);
		$group_buy = array_merge($group_buy, $stat);
	
		/* 计算当前价 */
		$cur_price = $price_ladder[0]['price']; // 初始化
		$cur_amount = $stat['valid_goods'] + $current_num; // 当前数量
		foreach ($price_ladder as $amount_price) {
			if ($cur_amount >= $amount_price['amount']) {
				$cur_price = $amount_price['price'];
			} else {
				break;
			}
		}
		$group_buy['cur_price'] = $cur_price;
		$group_buy['formated_cur_price'] = price_format($cur_price, false);
	
		/* 最终价 */
		$group_buy['trans_price'] = $group_buy['cur_price'];
		$group_buy['formated_trans_price'] = $group_buy['formated_cur_price'];
		$group_buy['trans_amount'] = $group_buy['valid_goods'];
	
		/* 状态 */
		$group_buy['status'] = $this->group_buy_status($group_buy);
		if (L('gbs.' . $group_buy['status']) != '') {
			$group_buy['status_desc'] = L('gbs.' . $group_buy['status']);
		}
	
		$group_buy['start_time'] = $group_buy['formated_start_date'];
		$group_buy['end_time'] = $group_buy['formated_end_date'];
		$group_buy['act_banner'] = $group_buy['act_banner'];
		$group_buy['click_num'] = $group_buy['click_num'];
		//$group_buy['sales_count'] = $group_buy['sales_count'] ? $group_buy['sales_count'] : 0;
	
	
		return $group_buy;
	}
	
	/**
	 * 获得团购的状态
	 *
	 * @access  public
	 * @param   array
	 * @return  integer
	 */
	public function group_buy_status($group_buy) {
		$now = gmtime();
		if ($group_buy['is_finished'] == 0) {
			/* 未处理 */
			if ($now < $group_buy['start_time']) {
				$status = GBS_PRE_START;
			} elseif ($now > $group_buy['end_time']) {
				$status = GBS_FINISHED;
			} else {
				if ($group_buy['restrict_amount'] == 0 || $group_buy['valid_goods'] < $group_buy['restrict_amount']) {
					$status = GBS_UNDER_WAY;
				} else {
					$status = GBS_FINISHED;
				}
			}
		} elseif ($group_buy['is_finished'] == GBS_SUCCEED) {
			/* 已处理，团购成功 */
			$status = GBS_SUCCEED;
		} elseif ($group_buy['is_finished'] == GBS_FAIL) {
			/* 已处理，团购失败 */
			$status = GBS_FAIL;
		}
	
		return $status;
	}
	
	/*
	 * 取得某团购活动统计信息
	 * @param   int     $group_buy_id   团购活动id
	 * @param   float   $deposit        保证金
	 * @return  array   统计信息
	 *                  total_order     总订单数
	 *                  total_goods     总商品数
	 *                  valid_order     有效订单数
	 *                  valid_goods     有效商品数
	 */
	
	public function group_buy_stat($group_buy_id, $deposit) {
		$model = new Model();
		$group_buy_id = intval($group_buy_id);
	
		/* 取得团购活动商品ID */
		$goods_activity = D('goods_activity');
		$where  = array('act_id'=>$group_buy_id,'act_type'=>GAT_GROUP_BUY);
		$group_buy_goods_id = $goods_activity->where($where)->getField('goods_id');
	
		/* 取得总订单数和总商品数 */
		$sql = "SELECT COUNT(*) AS total_order, SUM(g.goods_number) AS total_goods " .
				"FROM " . C('DB_PREFIX') . "order_info AS o, " .
				C('DB_PREFIX') . "order_goods AS g " .
				" WHERE o.order_id = g.order_id " .
				"AND o.extension_code = 'group_buy' " .
				"AND o.extension_id = '$group_buy_id' " .
				"AND g.goods_id = '$group_buy_goods_id' " .
				"AND (order_status = '" . OS_CONFIRMED . "' OR order_status = '" . OS_UNCONFIRMED . "')";
		$res = $model->query($sql);
		$stat = current($res);
		if ($stat['total_order'] == 0) {
			$stat['total_goods'] = 0;
		}
	
		/* 取得有效订单数和有效商品数 */
		$deposit = floatval($deposit);
		if ($deposit > 0 && $stat['total_order'] > 0) {
			$sql .= " AND (o.money_paid + o.surplus) >= '$deposit'";
			$res = $model->query($sql);
			$row = current($res);
			$stat['valid_order'] = $row['total_order'];
			if ($stat['valid_order'] == 0) {
				$stat['valid_goods'] = 0;
			} else {
				$stat['valid_goods'] = $row['total_goods'];
			}
		} else {
			$stat['valid_order'] = $stat['total_order'];
			$stat['valid_goods'] = $stat['total_goods'];
		}
	
		return $stat;
	}
	
	/**
	 *  返回虚拟卡信息
	 *
	 * @access  public
	 * @param
	 *
	 * @return void
	 */
	public function virtual_card_result($order_sn='', $goods) {
		/* 获取已经发送的卡片数据 */
		$virtual_card = D('virtual_card');
		$map = array('goods_id'=>$goods['goods_id'],'order_sn'=>$order_sn);
		$array = $virtual_card->field('card_sn, card_password, end_date, crc32')->where($map)->find();
	
		$cards = array();
		foreach ($array as $key=>$row){
			/* 卡号和密码解密 */
			if ($row['crc32'] == 0 || $row['crc32'] == crc32(AUTH_KEY)) {
				$row['card_sn'] = decrypt($row['card_sn']);
				$row['card_password'] = decrypt($row['card_password']);
			} elseif ($row['crc32'] == crc32(OLD_AUTH_KEY)) {
				$row['card_sn'] = decrypt($row['card_sn'], OLD_AUTH_KEY);
				$row['card_password'] = decrypt($row['card_password'], OLD_AUTH_KEY);
			} else {
				$row['card_sn'] = '***';
				$row['card_password'] = '***';
			}
	
			$cards[] = array('card_sn' => $row['card_sn'], 'card_password' => $row['card_password'], 'end_date' => date(C('date_format'), $row['end_date']));
		}
	
		return $cards;
	}
	
	/**
	* 记录帐户变动
	* @param   int     $user_id        用户id
	* @param   float   $user_money     可用余额变动
	* @param   float   $frozen_money   冻结余额变动
	* @param   int     $rank_points    等级积分变动
	* @param   int     $pay_points     消费积分变动
	* @param   string  $change_desc    变动说明
	* @param   int     $change_type    变动类型：参见常量文件
	* @return  void
	*/
	public function log_account_change($user_id, $user_money = 0, $frozen_money = 0, $rank_points = 0, $pay_points = 0, $change_desc = '', $change_type = ACT_OTHER) {
	    /* 插入帐户变动记录 */
	    $account_log = array(
	        'user_id' => $user_id,
	        'user_money' => $user_money,
	        'frozen_money' => $frozen_money,
	        'rank_points' => $rank_points,
	        'pay_points' => $pay_points,
	        'change_time' => gmtime(),
	        'change_desc' => $change_desc,
	        'change_type' => $change_type
	    );
	    M('account_log')->add($account_log);
	    /* 更新用户信息 */
	    $sql = "UPDATE " . C('DB_PREFIX') .
	    "users SET user_money = user_money + ('$user_money')," .
	    " frozen_money = frozen_money + ('$frozen_money')," .
	    " rank_points = rank_points + ('$rank_points')," .
	    " pay_points = pay_points + ('$pay_points')" .
	    " WHERE user_id = '$user_id' LIMIT 1";
	    $Model=new Model();
	    $Model->execute($sql);
	}
	
	/**
	 * 发红包：发货时发红包
	 * @param   int     $order_id   订单号
	 * @return  bool
	 */
	function send_order_bonus($order_id) {
	    $model = new Model();
	    /* 取得订单应该发放的红包 */
	    $bonus_list = $this->order_bonus($order_id);
	
	    /* 如果有红包，统计并发送 */
	    if ($bonus_list) {
	        /* 用户信息 */
	        $sql = "SELECT u.user_id, u.user_name, u.email " .
	            "FROM " . C('DB_PREFIX') . "order_info AS o, " .
	            C('DB_PREFIX') . "users AS u " .
	            "WHERE o.order_id = '$order_id' " .
	            "AND o.user_id = u.user_id  limit 1";
	        $user = $model->query($sql);
	        $user=$user[0];
	        /* 统计 */
	        $count = 0;
	        $money = '';
	        foreach ($bonus_list AS $bonus) {
	            $count += $bonus['number'];
	            $money .= price_format($bonus['type_money']) . ' [' . $bonus['number'] . '], ';
	
	            /* 修改用户红包 */
	            $sql = "INSERT INTO " . C('DB_PREFIX') . "user_bonus (bonus_type_id, user_id) " .
	                "VALUES('$bonus[type_id]', '$user[user_id]')";
	            for ($i = 0; $i < $bonus['number']; $i++) {
	                if (!$model->execute($sql)) {
	                    return $model->getError();
	                }
	            }
	        }
	
	        /* 如果有红包，发送邮件 */
	        /*if ($count > 0) {
	            $tpl = model('Base')->get_mail_template('send_bonus');
	            ECTouch::view()->assign('user_name', $user['user_name']);
	            ECTouch::view()->assign('count', $count);
	            ECTouch::view()->assign('money', $money);
	            ECTouch::view()->assign('shop_name', C('shop_name'));
	            ECTouch::view()->assign('send_date', local_date(C('date_format')));
	            ECTouch::view()->assign('sent_date', local_date(C('date_format')));
	            $content = ECTouch::view()->fetch('str:' . $tpl['template_content']);
	            send_mail($user['user_name'], $user['email'], $tpl['template_subject'], $content, $tpl['is_html']);
	        }*/
	    }
	
	    return true;
	}
	
	/**
	 * 取得订单应该发放的红包
	 * @param   int     $order_id   订单id
	 * @return  array
	 */
	function order_bonus($order_id) {
	    $model = new Model();
	    /* 查询按商品发的红包 */
	    $day = getdate();
	    $today = local_mktime(23, 59, 59, $day['mon'], $day['mday'], $day['year']);
	
	    $sql = "SELECT b.type_id, b.type_money, SUM(o.goods_number) AS number " .
	        "FROM " . C('DB_PREFIX') . "order_goods AS o, " .
	        C('DB_PREFIX') . "goods AS g, " .
	        C('DB_PREFIX') . "bonus_type AS b " .
	        " WHERE o.order_id = '$order_id' " .
	        " AND o.is_gift = 0 " .
	        " AND o.goods_id = g.goods_id " .
	        " AND g.bonus_type_id = b.type_id " .
	        " AND b.send_type = '" . SEND_BY_GOODS . "' " .
	        " AND b.send_start_date <= '$today' " .
	        " AND b.send_end_date >= '$today' " .
	        " GROUP BY b.type_id ";
	    $list = $model->query($sql);
	
	    /* 查询订单中非赠品总金额 */
	    $amount = $this->order_amount($order_id, false);
	
	    /* 查询订单日期 */
	    $sql = "SELECT add_time " .
	        " FROM " . C('DB_PREFIX') .
	        "order_info WHERE order_id = '$order_id' LIMIT 1";
	    $res = $model->query($sql);
	    $res=$res[0];
	    $order_time = $res['add_time'];
	    /* 查询按订单发的红包 */
	    $sql = "SELECT type_id, type_money, IFNULL(FLOOR('$amount' / min_amount), 1) AS number " .
	    "FROM " . C('DB_PREFIX') .
	    "bonus_type WHERE send_type = '" . SEND_BY_ORDER . "' " .
	    "AND send_start_date <= '$order_time' " .
	    "AND send_end_date >= '$order_time' ";
	    $list = array_merge($list, $model->query($sql));
	    
	    return $list;
	}
	
	/**
	 * 取得订单总金额
	 * @param   int     $order_id   订单id
	 * @param   bool    $include_gift   是否包括赠品
	 * @return  float   订单总金额
	 */
	public function order_amount($order_id, $include_gift = true) {
	    $sql = "SELECT SUM(goods_price * goods_number) " .
	        "as amount FROM " . C('DB_PREFIX') .
	        "order_goods WHERE order_id = '$order_id'";
	    if (!$include_gift) {
	        $sql .= " AND is_gift = 0 limit 1";
	    }
	    $model = new Model();
	    $res = $model->query($sql);
	    return floatval($res[0]['amount']);
	}
	
	// 增加销量统计
	public function add_touch_goods($flow_type, $extension_code) {
	    /* 统计时间段 */
	    $period = C('top10_time');
	    //近一个月（30天）
	    if ($period == 1) { // 一年
	        $ext = " AND o.add_time > '" . local_strtotime('-1 years') . "'";
	    } elseif ($period == 2) { // 半年
	        $ext = " AND o.add_time > '" . local_strtotime('-6 months') . "'";
	    } elseif ($period == 3) { // 三个月
	        $ext = " AND o.add_time > '" . local_strtotime('-3 months') . "'";
	    } elseif ($period == 4) { // 一个月
	        $ext = " AND o.add_time > '" . local_strtotime('-1 months') . "'";
	    } else {
	        $ext = '';
	    }
	    //查询销量统计表中是否有购物车中的商品信息
	    $sql = 'select goods_id from ' . C('DB_PREFIX') . 'cart where  session_id = "' . SESS_ID . '" AND rec_type = "' . $flow_type . '"';
	    $model = new Model();
	    $arrGoodsid = $model->query($sql);
	    foreach ($arrGoodsid as $key=>$goodsid) {
	        /* 查询该商品销量 */
	        $sql = 'SELECT IFNULL(SUM(g.goods_number), 0) ' .
	            'as count FROM ' . C('DB_PREFIX') . 'order_info AS o, ' .
	            C('DB_PREFIX') . 'order_goods AS g ' .
	            "WHERE o.order_id = g.order_id " .
	            "AND o.extension_code = '$extension_code'  AND g.goods_id = '" . $goodsid['goods_id'] . "' AND o.pay_status = '2' " . $ext;
	        $res = $model->query($sql);
	        $res=$res[0];
	        $sales_count = $res['count'];
	        if ($flow_type == CART_GENERAL_GOODS) {
	            $nCount = $model->query('select COUNT(*) as count from ' . C('DB_PREFIX') . 'touch_goods where  goods_id = "' . $goodsid['goods_id'] . '"');
	            $nCount = current($nCount);
	            if ($nCount['count'] == 0) {
	                $model->execute("INSERT INTO " . C('DB_PREFIX') . "touch_goods (`goods_id` ,`sales_volume` ) VALUES ( '" . $goodsid['goods_id'] . "' , '0')");
	            }
	            $sql = 'update ' . C('DB_PREFIX') . 'touch_goods AS a set a.sales_volume = ' . $sales_count . " WHERE goods_id=" . $goodsid['goods_id'];
	            $model->execute($sql);
	        }
	        if ($flow_type == CART_GROUP_BUY_GOODS) {
	            /* 查询该商品销量 */
	            $sql = 'SELECT IFNULL(SUM(g.goods_number), 0) ' .
	                'as count FROM ' . C('DB_PREFIX') . 'order_info AS o LEFT JOIN ' .
	                C('DB_PREFIX') . 'order_goods AS g  ON o.order_id = g.order_id ' .
	                'LEFT JOIN ' . C('DB_PREFIX') . 'goods_activity as ga ON ga.goods_id = g.goods_id ' .
	                "WHERE o.extension_code = '$extension_code'  AND o.pay_status = 2  AND g.goods_id = '" . $goodsid['goods_id'] . "'" . $ext;
	            $res = $model->query($sql);
	            $res = current($res);
	            
	            $nCount = $this->query('select COUNT(*) as count from ' . C('DB_PREFIX') .
	                'touch_goods_activity tga LEFT JOIN ' . C('DB_PREFIX') . 'goods_activity ga ON tga.act_id =ga.act_id  where  ga.goods_id = "' . $goodsid['goods_id'] . '" ');
	            $nCount = current($nCount);
	            
	            $sql = 'SELECT act_id FROM ' . C('DB_PREFIX') . 'goods_activity WHERE goods_id = "' . $goodsid['goods_id'] . '" ';
	            $act_id = $model->query($sql);
	            $activity = current($act_id);
	            
	            if ($nCount['count'] == 0) {
	                $model->execute("INSERT INTO " . C('DB_PREFIX') . "touch_goods_activity (`act_id` ,`sales_count` ) VALUES ( '" . $activity['act_id'] . "' , '0')");
	            }
	            $sales_count_group = $res['count'];
	            $sql = 'update ' . C('DB_PREFIX') . 'touch_goods_activity set sales_count = ' . $sales_count_group . " WHERE act_id = $activity[act_id]";
	            $model->execute($sql);
	        }
	    }
	}
	
	/**
	 * 将支付LOG插入数据表
	 * @access  public
	 * @param   integer     $id         订单编号
	 * @param   float       $amount     订单金额
	 * @param   integer     $type       支付类型
	 * @param   integer     $is_paid    是否已支付
	 * @return  int
	 */
	public function insert_pay_log($id, $amount, $type = PAY_SURPLUS, $is_paid = 0) {
	    $data['order_id'] = $id;
	    $data['order_amount'] = $amount;
	    $data['order_type'] = $type;
	    $data['is_paid'] = $is_paid;
	    return M('pay_log')->add($data);
	}
	
	/**
	 * 取得支付方式信息
	 * @param   int     $pay_id     支付方式id
	 * @return  array   支付方式信息
	 */
	public function payment_info($pay_id) {
	    $where=array(
	        'pay_id'=>$pay_id,
	        'enabled'=>1
	    );
	    return M('payment')->where($where)->find();
	}
	
	/**
	 * 取得可用的支付方式列表
	 * @param   bool    $support_cod        配送方式是否支持货到付款
	 * @param   int     $cod_fee            货到付款手续费（当配送方式支持货到付款时才传此参数）
	 * @param   int     $is_online          是否支持在线支付
	 * @return  array   配送方式数组
	 */
	public function available_payment_list($support_cod, $cod_fee = 0, $is_online = false) {
	    $sql = 'SELECT pay_id, pay_code, pay_name, pay_fee, pay_desc, pay_config, is_cod' .
	        ' FROM ' . C('DB_PREFIX') . 'payment WHERE enabled = 1 ';
	    if (!$support_cod) {
	        $sql .= 'AND is_cod = 0 '; // 如果不支持货到付款
	    }
	    if ($is_online) {
	        $sql .= "AND is_online = '1' ";
	    }
	    $sql .= 'ORDER BY pay_order'; // 排序
	    $model=new Model();
	    $res = $model->query($sql);
	
	    $pay_list = array();
	    foreach ($res as $key => $row) {
	        if ($row['is_cod'] == '1') {
	            $row['pay_fee'] = $cod_fee;
	        }
	        $row['format_pay_fee'] = strpos($row['pay_fee'], '%') !== false ? $row['pay_fee'] :
	        price_format($row['pay_fee'], false);
	        $modules[] = $row;
	    }
	    if (isset($modules)) {
	        return $modules;
	    }
	}
	/*
	 * 按配送区域自动分派仓库
	 * */
	public function auto_updateorder_warehouse($user_id,$order_id,$shipping_id,$address_id, $is_196=0){
	    $where['user_id']=$user_id;
	    $where['order_id']=$order_id;
	    $order_info=M('order_info');
        if($shipping_id!=2){
            $address = D("Useraddress")->get_address_by_id($address_id);
            $gps = M("landmark_repair")->where(array("name"=>$address['sign_building'],"district_id"=>$address['district_id']))->field("lat,lng")->find();

            if($gps['lat']>0){
                $address_gps['longitude'] = $gps['lat'];
                $address_gps['latitude'] = $gps['lng'];
            }else {
                if ($address['is_ok'] == 1 && !empty($address['longitude']) && !empty($address['latitude'])) {
                    //已确认坐标
                    $address_gps = $address;
                } else {
                    $address_gps = address_to_gps_amap($address['address_building'], $address['city']);
                }
            }
            $lnglat['lat'] = $address_gps['latitude'];
            $lnglat['lng'] = $address_gps['longitude'];
        }else{
            //非配送单
            return null;
        }
        $arr = D("Users")->get_distribution_by_gps($lnglat['lng'],$lnglat['lat']);
        if($arr['wdr_id']>0){
            $wid = $arr['wid'];
            $wdr_id = $arr['wdr_id'];
            //查询是否为196用户，196用户：仓库id用主仓对应的虚拟仓
            if($is_196){
                $wid_196 = M('warehouse')->where(array('pid' => $wid))->getField('id');
                $wid = $wid_196 ? $wid_196 : $wid;
            }
            $savedata=array(
                'wid'=> $wid,
                'wdr_id'=>$wdr_id
            );
            $order_info->where($where)->save($savedata);

            return $wid;
        }else{
            returnApiError("重新检查地址");
        }
	}

/*
 * 设置默认配送时间
 * */	
public function default_deliverytime($paytime,$day=1){
    if(empty($paytime)){
        $paytime=local_date('Y-m-d',time());
    }
    $delivery_time = local_strtotime($paytime.' +'.$day.' day '.C('DEFAULT_PRESELL_TIME_H'));
    $new_data = date('Y-m-d',$delivery_time);
    $delivery_time=strtotime($new_data." 22:00:00");
    $start_time=strtotime($new_data." 10:00:00");
    return array('delivery_time'=>$delivery_time,'start_time'=>$start_time);
}

/*
 * 将预售商品与常规商品分单
 * */
public function split_single($order,$log_id){
    set_time_limit(0);
    $order_goods_mod=M('order_goods');
    $order_goods=$order_goods_mod->alias('og')
    ->field('og.rec_id,og.goods_id,og.goods_price,og.is_presell,og.buckle_inventory,og.goods_number,og.order_id,og.act_id,og.giving,g.delivery_type,g.delivery_cycle')
    ->join(C ( 'DB_PREFIX' ) .'goods as g on g.goods_id=og.goods_id')
    ->where(array('og.order_id'=>$order['order_id']))
    ->select();
    $order_list = array();
    if($order_goods){
        $order_info_mod=M('order_info');
        $batch_no=$log_id;
        $is_include_presell=0;// 0-未包含预售   1-包含预售
        $order_goods_count=count($order_goods);//订单商品数
        if($order_goods_count==1){
            if($order_goods[0]['is_presell']==1){
                $is_include_presell=1;
                if($order_goods[0]['delivery_type']==1){//分段发货
                    $delivery_time=$this->check_shippingtime($order_goods[0]['goods_id'],$order['pay_time']);
                    if($delivery_time){
                        $new_data = date('Y-m-d',$delivery_time);
                        $delivery_time=strtotime($new_data." 22:00:00");
                        $start_time=strtotime($new_data." 10:00:00");
                    }else{
                        /*
                         * 默认为次日发货时间
                         * */
                        $pay_time=local_date('Y-m-d',$order['pay_time']);
                        $deliveryarr=$this->default_deliverytime($pay_time);
                        $delivery_time=$deliveryarr['delivery_time'];
                        $start_time=$deliveryarr['start_time'];
                    }
                }elseif($order_goods[0]['delivery_type']==2){//定时方式
                    if($order_goods[0]['delivery_cycle']){
                        $pay_time=local_date('Y-m-d',$order['pay_time']);
                        $delivery_time = local_strtotime($pay_time.' +'.$order_goods[0]['delivery_cycle'].' day '.C('DEFAULT_PRESELL_TIME_H'));
                        if(empty($delivery_time)){
                            /*
                             * 默认为次日发货时间
                             * */
                            $pay_time=local_date('Y-m-d',$order['pay_time']);
                            $deliveryarr=$this->default_deliverytime($pay_time);
                            $delivery_time=$deliveryarr['delivery_time'];
                            $start_time=$deliveryarr['start_time'];
                        }else{
                            $new_data = date('Y-m-d',$delivery_time);
                            $delivery_time=strtotime($new_data." 22:00:00");
                            $start_time=strtotime($new_data." 10:00:00");
                        }
                    }else{
                        /*
                         * 默认为次日发货时间
                         * */
                        $pay_time=local_date('Y-m-d',$order['pay_time']);
                        $best_time=date('Y-m-d',$order['best_time']);
                        if($order_goods[0]['delivery_cycle']==0 && $best_time===$pay_time){ //当日达
                            $deliveryarr=$this->default_deliverytime($pay_time,0);
                        }else{
                            $deliveryarr=$this->default_deliverytime($pay_time);
                        }
                        $delivery_time=$deliveryarr['delivery_time'];
                        $start_time=$deliveryarr['start_time'];
                    }
                }else{
                    /*
                     * 默认为次日发货时间
                     * */
                    $pay_time=local_date('Y-m-d',$order['pay_time']);
                    $deliveryarr=$this->default_deliverytime($pay_time);
                    $delivery_time=$deliveryarr['delivery_time'];
                    $start_time=$deliveryarr['start_time'];
                }
                $orderolddata=array(
                    'batch_no'=>$batch_no,
                    'best_time_start'=>$start_time,
                    'best_time'=>$delivery_time,
                    'is_presell'=>$is_include_presell,
                );
                if($order['buckle_inventory']==1){
                    if($order['shipping_id']==2){
						//确认收货不修改配货状态
						if($order['shipping_status']!=2){
							$orderolddata['shipping_status']=0;
						}
                        //若现售订单，自提时间显示为下单日期-10:00-22:00
                        //若自提订单下单时间超过晚上9点半，则自提时间显示为 下单日期的次日 10:00-22:00
                        $addtiem = $order['add_time'];
                        //                         $check_time = strtotime(date('Y-m-d',$order['add_time'])." 21:30:00");

                        //自提订单超过22点后配送日期为次日10:00-22:30
                        $check_time = strtotime(date('Y-m-d',$order['add_time'])." 22:00:00");
                        if($addtiem>=$check_time){
                            $orderolddata['best_time'] = strtotime(date('Y-m-d',$order['add_time'])." 22:00:00")+86400;
                            //                             $orderolddata['best_time_start'] = strtotime(date('Y-m-d',$order['add_time'])." 10:00:00")+86400;
                            //                             $orderolddata['best_time'] = strtotime(date('Y-m-d',$order['add_time'])." 22:30:00")+86400;
                            $orderolddata['best_time_start'] = strtotime(date('Y-m-d',$order['add_time'])." 10:00:00")+86400;
                        }else{
                            $orderolddata['best_time'] = strtotime(date('Y-m-d',$order['add_time'])." 22:00:00");
                            $orderolddata['best_time_start'] = strtotime(date('Y-m-d',$order['add_time'])." 10:00:00");
                        }
                    }
                }else{
                    if($order['shipping_id']==2){
						//确认收货不修改配货状态
						if($order['shipping_status']!=2) {
							$orderolddata['shipping_status'] = 0;
						}
                        //预售订单，自提时间显示最早发货日期-10:00-22:00
                        $orderolddata['best_time'] = strtotime(date('Y-m-d',$orderolddata['best_time'])." 22:00:00");
                        //                         $orderolddata['best_time'] = strtotime(date('Y-m-d',$orderolddata['best_time'])." 22:30:00");
                        $orderolddata['best_time_start'] = strtotime(date('Y-m-d',$orderolddata['best_time_start'])." 10:00:00");
                    }
                }

                $order_info_mod->where(array('order_id'=>$order['order_id']))->save($orderolddata);
                $order['best_time'] = $orderolddata['best_time'];
                $order['best_time_start'] = $orderolddata['best_time_start'];
                $order_list[]= $order;
                $this->goods_sell_notily($order);
                return $order_list;
            }else{
                $orderolddata=array(
                    'is_presell'=>$is_include_presell,
                );
                if($order['shipping_id']==2){
					//确认收货不修改配货状态
					if($order['shipping_status']!=2) {
						$orderolddata['shipping_status'] = 0;
					}
                    //若现售订单，自提时间显示为下单日期-10:00-22:30
                    //若自提订单下单时间超过晚上9点半，则自提时间显示为 下单日期的次日 10:00-22:30
                }
                $order_info_mod->where(array('order_id'=>$order['order_id']))->save($orderolddata);
                $order_list[]= $order;
                $this->goods_sell_notily($order);
                return $order_list;
            }
        }else{
            $goods_amount=0;
            $i=0;//记录预售分单个数
            $order_goods_count=$order_goods_count-1;
            $orderbesttime=array();//根据预售商品发货时间进行分组
            $goods_mod= M('goods');
            $presell_flas='';//分单类型标识符前缀
            $gif_goods_list = array();//存放参与活动商品信息(赠品，换购商品，抢购商品)
            foreach ($order_goods as $ka=>$va ){
                 if($va['act_id']>0 && in_array($va['giving'], array(1,2))){
                    $gif_goods_list[]=$va;
                    unset($order_goods[$ka]);
                 }
            }
            $max_timeval=array();//记录同一活动下面最晚时间
            foreach ($order_goods as $k=>$v){
                 if($v['is_presell']==1){
                     $presell_flas='is_presell_1';
                     $is_auto_morrow_presell=$goods_mod->where(array('goods_id'=>$v['goods_id']))->getField('is_auto_morrow_presell');
                     if($is_auto_morrow_presell==1){
                         $presell_flas='morrow_presell';
                     }
                     if($v['delivery_type']==1){//分段发货
                         $delivery_time=$this->check_shippingtime($v['goods_id'],$order['pay_time']);
                         if($delivery_time){
                             $new_data = date('Y-m-d',$delivery_time);
                             $delivery_time=strtotime($new_data." 22:00:00");
                             $start_time=strtotime($new_data." 10:00:00");
                             $v['best_time']=$delivery_time;
                             $v['best_time_start']=$start_time;
                             if($v['act_id']>0 && (empty($max_timeval[$v['act_id']]) || $max_timeval[$v['act_id']]['best_time']<$v['best_time'])){
                                 $max_timeval[$v['act_id']]=array('best_time'=>$v['best_time'],'ordertimekey'=>$presell_flas.'_'.$v['best_time']);
                             }
                             $orderbesttime[$presell_flas.'_'.$v['best_time']][]=$v;
                         }else{
                             /*
                              * 默认为次日发货时间
                              * */
                             $pay_time=local_date('Y-m-d',$order['pay_time']);
                             $deliveryarr=$this->default_deliverytime($pay_time);
                             $v['best_time']=$deliveryarr['delivery_time'];
                             $v['best_time_start']=$deliveryarr['start_time'];
                             if($v['act_id']>0 && (empty($max_timeval[$v['act_id']]) || $max_timeval[$v['act_id']]['best_time']<$v['best_time'])){
                                 $max_timeval[$v['act_id']]=array('best_time'=>$v['best_time'],'ordertimekey'=>$presell_flas.'_'.$v['best_time']);
                             }
                             $orderbesttime[$presell_flas.'_'.$v['best_time']][]=$v;
                              
                         }
                     }elseif($v['delivery_type']==2){//定时方式
                         if($v['delivery_cycle']){
                             $pay_time=local_date('Y-m-d',$order['pay_time']);
                             $delivery_time = local_strtotime($pay_time.' +'.$v['delivery_cycle'].' day '.C('DEFAULT_PRESELL_TIME_H'));
                             if(empty($delivery_time)){
                                 /*
                                  * 默认为次日发货时间
                                  * */
                                 $pay_time=local_date('Y-m-d',$order['pay_time']);
                                 $deliveryarr=$this->default_deliverytime($pay_time);
                                 $v['best_time']=$deliveryarr['delivery_time'];
                                 $v['best_time_start']=$deliveryarr['start_time'];
                                 $v['include_presell']=$is_include_presell;
                                 if($v['act_id']>0 && (empty($max_timeval[$v['act_id']]) || $max_timeval[$v['act_id']]['best_time']<$v['best_time'])){
                                     $max_timeval[$v['act_id']]=array('best_time'=>$v['best_time'],'ordertimekey'=>$presell_flas.'_'.$v['best_time']);
                                 }
                                 $orderbesttime[$presell_flas.'_'.$v['best_time']][]=$v;
                             }
                             $new_data = date('Y-m-d',$delivery_time);
                             $delivery_time=strtotime($new_data." 22:00:00");
                             $start_time=strtotime($new_data." 10:00:00");
                             $v['best_time']=$delivery_time;
                             $v['best_time_start']=$start_time;
                             if($v['act_id']>0 && (empty($max_timeval[$v['act_id']]) || $max_timeval[$v['act_id']]['best_time']<$v['best_time'])){
                                 $max_timeval[$v['act_id']]=array('best_time'=>$v['best_time'],'ordertimekey'=>$presell_flas.'_'.$v['best_time']);
                             }
                             $orderbesttime[$presell_flas.'_'.$v['best_time']][]=$v;
                         }else{
                             /*
                              * 默认为次日发货时间
                              * */
                             $pay_time=local_date('Y-m-d',$order['pay_time']);
                             $best_time=date('Y-m-d',$order['best_time']);
                             if($v['delivery_cycle']==0 && $best_time===$pay_time){ // 当日达
                                $deliveryarr=$this->default_deliverytime($pay_time,0);
                             }else{
                                 $deliveryarr=$this->default_deliverytime($pay_time);
                             }
                             $v['best_time']=$deliveryarr['delivery_time'];
                             $v['best_time_start']=$deliveryarr['start_time'];
                             if($v['act_id']>0 && (empty($max_timeval[$v['act_id']]) || $max_timeval[$v['act_id']]['best_time']<$v['best_time'])){
                                 $max_timeval[$v['act_id']]=array('best_time'=>$v['best_time'],'ordertimekey'=>$presell_flas.'_'.$v['best_time']);
                             }
                             $orderbesttime[$presell_flas.'_'.$v['best_time']][]=$v;
                         }
                     }else{
                         /*
                          * 默认为次日发货时间
                          * */
                         $pay_time=local_date('Y-m-d',$order['pay_time']);
                         $deliveryarr=$this->default_deliverytime($pay_time);
                         $v['best_time']=$deliveryarr['delivery_time'];
                         $v['best_time_start']=$deliveryarr['start_time'];
                         if($v['act_id']>0 && (empty($max_timeval[$v['act_id']]) || $max_timeval[$v['act_id']]['best_time']<$v['best_time'])){
                             $max_timeval[$v['act_id']]=array('best_time'=>$v['best_time'],'ordertimekey'=>$presell_flas.'_'.$v['best_time']);
                         }
                         $orderbesttime[$presell_flas.'_'.$v['best_time']][]=$v;
                     }
                 }else{
                     $presell_flas='is_presell_0';
                     $v['best_time']=$order['best_time'];
                     $v['best_time_start']=$order['best_time_start'];
                     if($v['act_id']>0 && (empty($max_timeval[$v['act_id']]) || $max_timeval[$v['act_id']]['best_time']<$v['best_time'])){
                         $max_timeval[$v['act_id']]=array('best_time'=>$v['best_time'],'ordertimekey'=>$presell_flas.'_'.$v['best_time']);
                     }
                     $orderbesttime[$presell_flas.'_'.$v['best_time']][]=$v;
                 }
             }
             
             $goods_amount_sum=0;
             $orderbesttime_count=count($orderbesttime);
             $i=1;
             /*dump($gif_goods_list);
             dump($max_timeval);
             dump($orderbesttime);*/
             
             // 将存放参与活动商品信息(赠品，换购商品，抢购商品)，进行塞
             $gif_goods_list_count=count($gif_goods_list);
             //echo $gif_goods_list_count;
             if($gif_goods_list_count>0){
                $orderbesttime=$this->add_gift_goods($gif_goods_list, $orderbesttime,$max_timeval);
             }
             /*dump($orderbesttime);
             exit;*/
             foreach ($orderbesttime as $key=>$val){
                 $goods_amount=0;
                 $orderdata=$order;
                 unset($orderdata['order_id']);
                 $rec_id=array();
                 $best_time=0;
                 $flas=true;
                 $is_presell=0;
                 foreach ($val as $kk=>$vv){
                     $rec_id[]=$vv['rec_id'];
                     $amount=$vv['goods_price']*$vv['goods_number'];
                     $goods_amount=$goods_amount+$amount;
                     if($flas){
                         $best_time=$vv['best_time'];
                         $start_time=$vv['best_time_start'];
                         $flas=false;
                     }
                     if($vv['is_presell']==1 && $vv['buckle_inventory']==0){
                         $is_presell=1;
                     }
                 }
                 if($orderbesttime_count==1){
                     $orderolddata=array(
                         'batch_no'=>$batch_no,
                         'is_presell'=>$is_presell,
                         'best_time'=>$best_time,
                         'best_time_start'=>$start_time,
                     );
                     if($order['shipping_id']==2){
                         if($is_presell==1){
							 //确认收货不修改配货状态
							 if($order['shipping_status']!=2) {
								 $orderolddata['shipping_status'] = 0;
							 }
                             //预售订单，自提时间显示最早发货日期-10:00-22:00
                             $orderolddata['best_time'] = strtotime(date('Y-m-d',$orderolddata['best_time'])." 22:00:00");
                             $orderolddata['best_time_start'] = strtotime(date('Y-m-d',$orderolddata['best_time_start'])." 10:00:00");
                         }else{
							 if($order['shipping_status']!=2) {
								 $orderolddata['shipping_status'] = 0;
							 }

                             //若现售订单，自提时间显示为下单日期-10:00-22:00
                             //若自提订单下单时间超过晚上9点半，则自提时间显示为 下单日期的次日 10:00-22:00
                         }
                     }
                     if($is_presell==1){
                         $orderolddata['buckle_inventory']=0;
                     }
                     //修改原订单商品总价，支付总额
                     $order_info_mod->where(array('order_id'=>$order['order_id']))->save($orderolddata);
                     $order['best_time']=$orderolddata['best_time'];
                     $order['best_time_start']=$orderolddata['best_time_start'];
                     $order_list[]= $order;
					 $this->goods_sell_notily($order);
                     return $order_list;
                 }
                 if($orderbesttime_count==$i){
                     $orderolddata=array(
                         'goods_amount'=>$order['goods_amount']-$goods_amount_sum,
                         'batch_no'=>$batch_no,
                         'is_presell'=>$is_presell,
                         'best_time'=>$best_time,
                         'best_time_start'=>$start_time,
                     );
                      
                     if($order['shipping_id']==2){
                         if($is_presell==1){
							 if($order['shipping_status']!=2) {
								 $orderolddata['shipping_status'] = 0;
							 }
                             //预售订单，自提时间显示最早发货日期-10:00-22:00
                             $orderolddata['best_time'] = strtotime(date('Y-m-d',$orderolddata['best_time'])." 22:00:00");
                             $orderolddata['best_time_start'] = strtotime(date('Y-m-d',$orderolddata['best_time_start'])." 10:00:00");
                         }else{
							 if($order['shipping_status']!=2) {
								 $orderolddata['shipping_status'] = 0;
							 }

                             //若现售订单，自提时间显示为下单日期-10:00-22:00
                             //若自提订单下单时间超过晚上9点半，则自提时间显示为 下单日期的次日 10:00-22:00
                         }
                         if(in_array($order['pay_id'],array(0,1,2))){
                             $orderolddata['order_amount']=$order['order_amount']-$goods_amount_sum+$order['bonus']+$order['discount'];
                         }elseif ($order['pay_id']==3){
                             $orderolddata['surplus']=$order['surplus']-$goods_amount_sum+$order['bonus']+$order['discount'];
                         }
                     }elseif ($order['shipping_id']==3){
                         if(in_array($order['pay_id'],array(1,2))){
                             $orderolddata['money_paid']=$order['money_paid']-$goods_amount_sum+$order['bonus']+$order['discount'];
                         }elseif ($order['pay_id']==3){
                             $orderolddata['surplus']=$order['surplus']-$goods_amount_sum+$order['bonus']+$order['discount'];
                         }
                     }
                     if($is_presell==1){
                         $orderolddata['buckle_inventory']=0;
                     }
                     //修改原订单商品总价，支付总额
                     $order_info_mod->where(array('order_id'=>$order['order_id']))->save($orderolddata);
                     $order['best_time']=$orderolddata['best_time'];
                     $order['best_time_start']=$orderolddata['best_time_start'];
                     $order_list[]= $order;
					 $this->goods_sell_notily($order);
                     return $order_list;
                 }
                 $orderdata['order_sn']=get_order_sn();
                 $orderdata['order_amount']=0;
                 $orderdata['surplus']=0;
                 $orderdata['money_paid']=0;
                 $orderdata['goods_amount']=$goods_amount;
                 $goods_amount_sum=$goods_amount_sum+$goods_amount;
                 $orderdata['best_time']=$best_time;
                 $orderdata['best_time_start']=$start_time;
                 if($orderdata['shipping_id']==2){
                     if($is_presell==1){
						 if($order['shipping_status']!=2) {
							 $orderolddata['shipping_status'] = 0;
						 }
                         //预售订单，自提时间显示最早发货日期-10:00-22:00
                         $orderolddata['best_time'] = strtotime(date('Y-m-d',$orderolddata['best_time'])." 22:00:00");
                         $orderolddata['best_time_start'] = strtotime(date('Y-m-d',$orderolddata['best_time_start'])." 10:00:00");
                     }else{
						 if($order['shipping_status']!=2) {
							 $orderolddata['shipping_status'] = 0;
						 }

                         //若现售订单，自提时间显示为下单日期-10:00-22:00
                         //若自提订单下单时间超过晚上9点半，则自提时间显示为 下单日期的次日 10:00-22:00
                     }

                     if(in_array($orderdata['pay_id'],array(0,1,2))){
                         $orderdata['order_amount']=$goods_amount;
                     }elseif ($orderdata['pay_id']==3){
                         $orderdata['surplus']=$goods_amount;
                     }
                 }elseif ($orderdata['shipping_id']==3){
                     if(in_array($orderdata['pay_id'],array(1,2))){
                         $orderdata['money_paid']=$goods_amount;
                     }elseif ($orderdata['pay_id']==3){
                         $orderdata['surplus']=$goods_amount;
                     }
                 }
                 $orderdata['batch_no']=$batch_no;
                 $orderdata['is_presell']=$is_presell;
                 if($is_presell==1){
                     $orderdata['buckle_inventory']=0;
                 }
                 $order_id=$order_info_mod->add($orderdata);
                 if($order_id){
                     $rec_id=implode(',',$rec_id);
                     $order_goods_mod->where(array('rec_id'=>array('in',$rec_id)))->save(array('order_id'=>$order_id));
                     $orderdata['order_id'] = $order_id;
                     $order_list[] = $orderdata;
                 }
                 $i=$i+1;
             }
			 $this->goods_sell_notily($order);
             return $order_list;
         }
     }else{
	        $order_list[]= $order;
		 $this->goods_sell_notily($order);
	        return $order_list;
	}
}  

/**
 * @param unknown $goods_list 赠品以及换购商品
 * @param unknown $order_list 已分订单
 * @param unknown $order_list 属于同一个活动中最晚的订单
 * return $order_list
 */
private function add_gift_goods($goods_list,$order_list,$max_timeval){
    foreach ($goods_list as $key=>$goods){
        foreach($order_list as $okey=>$order_goods){
            foreach ($order_goods as $k=>$v){
                if($goods['act_id'] === $v['act_id'] && $max_timeval[$v['act_id']]['ordertimekey']===$okey){
                    $goods['best_time']=$v['best_time'];
                    $goods['best_time_start']=$v['best_time_start'];
                    $order_list[$okey][]=$goods;
                    break;
                }
            }
        }
    }
    return $order_list;
}
/*
 * 将预售商品与常规商品分单
 * */
public function split_single_bak0408($order,$log_id){
     set_time_limit(0);
     $order_goods_mod=M('order_goods');
     $order_goods=$order_goods_mod->alias('og')
     ->field('og.rec_id,og.goods_id,og.goods_price,og.is_presell,og.buckle_inventory,og.goods_number,og.order_id,og.act_id,og.giving,g.delivery_type,g.delivery_cycle')
     ->join(C ( 'DB_PREFIX' ) .'goods as g on g.goods_id=og.goods_id')
     ->where(array('og.order_id'=>$order['order_id']))
     ->select();
     $order_list = array();
     if($order_goods){
         $order_info_mod=M('order_info');
         $batch_no=$log_id;
         $is_include_presell=0;// 0-未包含预售   1-包含预售
         $order_goods_count=count($order_goods);//订单商品数
         if($order_goods_count==1){
             if($order_goods[0]['is_presell']==1){
                 $is_include_presell=1;
                 if($order_goods[0]['delivery_type']==1){//分段发货
                     $delivery_time=$this->check_shippingtime($order_goods[0]['goods_id'],$order['pay_time']);
                     if($delivery_time){
                         $new_data = date('Y-m-d',$delivery_time);
                         $delivery_time=strtotime($new_data." 22:00:00");
                         $start_time=strtotime($new_data." 10:00:00");
                     }else{
                         /*
                          * 默认为次日发货时间
                          * */
                         $pay_time=local_date('Y-m-d',$order['pay_time']);
                         $deliveryarr=$this->default_deliverytime($pay_time);
                         $delivery_time=$deliveryarr['delivery_time'];
                         $start_time=$deliveryarr['start_time'];
                     }
                 }elseif($order_goods[0]['delivery_type']==2){//定时方式
                     if($order_goods[0]['delivery_cycle']){
                         $pay_time=local_date('Y-m-d',$order['pay_time']);
                         $delivery_time = local_strtotime($pay_time.' +'.$order_goods[0]['delivery_cycle'].' day '.C('DEFAULT_PRESELL_TIME_H'));
                         if(empty($delivery_time)){
                             /*
                              * 默认为次日发货时间
                              * */
                             $pay_time=local_date('Y-m-d',$order['pay_time']);
                             $deliveryarr=$this->default_deliverytime($pay_time);
                             $delivery_time=$deliveryarr['delivery_time'];
                             $start_time=$deliveryarr['start_time'];
                         }else{
                             $new_data = date('Y-m-d',$delivery_time);
                             $delivery_time=strtotime($new_data." 22:00:00");
                             $start_time=strtotime($new_data." 10:00:00");
                         }
                     }else{
                         /*
                          * 默认为次日发货时间
                          * */
                         $pay_time=local_date('Y-m-d',$order['pay_time']);
                         $best_time=date('Y-m-d',$order['best_time']);
                         if($order_goods[0]['delivery_cycle']==0 && $best_time===$pay_time){ //当日达
                             $deliveryarr=$this->default_deliverytime($pay_time,0);
                         }else{
                             $deliveryarr=$this->default_deliverytime($pay_time);
                         }
                         $delivery_time=$deliveryarr['delivery_time'];
                         $start_time=$deliveryarr['start_time'];
                     }
                 }else{
                     /*
                      * 默认为次日发货时间
                      * */
                     $pay_time=local_date('Y-m-d',$order['pay_time']);
                     $deliveryarr=$this->default_deliverytime($pay_time);
                     $delivery_time=$deliveryarr['delivery_time'];
                     $start_time=$deliveryarr['start_time'];
                 }
                 $orderolddata=array(
                     'batch_no'=>$batch_no,
                     'best_time_start'=>$start_time,
                     'best_time'=>$delivery_time,
                     'is_presell'=>$is_include_presell,
                 );
                 if($order['buckle_inventory']==1){
                     if($order['shipping_id']==2){
						 if($order['shipping_status']!=2) {
							 $orderolddata['shipping_status'] = 0;
						 }
                         //若现售订单，自提时间显示为下单日期-10:00-22:00
                         //若自提订单下单时间超过晚上9点半，则自提时间显示为 下单日期的次日 10:00-22:00
                         $addtiem = $order['add_time'];
//                         $check_time = strtotime(date('Y-m-d',$order['add_time'])." 21:30:00");

                         //自提订单超过22点后配送日期为次日10:00-22:30
                         $check_time = strtotime(date('Y-m-d',$order['add_time'])." 22:00:00");
                         if($addtiem>=$check_time){
                             $orderolddata['best_time'] = strtotime(date('Y-m-d',$order['add_time'])." 22:00:00")+86400;
//                             $orderolddata['best_time_start'] = strtotime(date('Y-m-d',$order['add_time'])." 10:00:00")+86400;
//                             $orderolddata['best_time'] = strtotime(date('Y-m-d',$order['add_time'])." 22:30:00")+86400;
                             $orderolddata['best_time_start'] = strtotime(date('Y-m-d',$order['add_time'])." 10:00:00")+86400;
                         }else{
                             $orderolddata['best_time'] = strtotime(date('Y-m-d',$order['add_time'])." 22:00:00");
                             $orderolddata['best_time_start'] = strtotime(date('Y-m-d',$order['add_time'])." 10:00:00");
                         }
                     }
                 }else{
                     if($order['shipping_id']==2){
						 if($order['shipping_status']!=2) {
							 $orderolddata['shipping_status'] = 0;
						 }
                         //预售订单，自提时间显示最早发货日期-10:00-22:00
                         $orderolddata['best_time'] = strtotime(date('Y-m-d',$orderolddata['best_time'])." 22:00:00");
//                         $orderolddata['best_time'] = strtotime(date('Y-m-d',$orderolddata['best_time'])." 22:30:00");
                         $orderolddata['best_time_start'] = strtotime(date('Y-m-d',$orderolddata['best_time_start'])." 10:00:00");
                     }
                 }

                 $order_info_mod->where(array('order_id'=>$order['order_id']))->save($orderolddata);
                 $order['best_time'] = $orderolddata['best_time'];
                 $order['best_time_start'] = $orderolddata['best_time_start'];
                 $order_list[]= $order;
				 $this->goods_sell_notily($order);
                 return $order_list;
             }else{
                 $orderolddata=array(
                     'is_presell'=>$is_include_presell,
                 );
                 if($order['shipping_id']==2){
					 if($order['shipping_status']!=2) {
						 $orderolddata['shipping_status'] = 0;
					 }
                     //若现售订单，自提时间显示为下单日期-10:00-22:30
                     //若自提订单下单时间超过晚上9点半，则自提时间显示为 下单日期的次日 10:00-22:30
                     $addtiem = $order['add_time'];
//                     $check_time = strtotime(date('Y-m-d',$order['add_time'])." 21:30:00");
//                     当天22：00之后的订单默认为次日
                     $check_time = strtotime(date('Y-m-d',$order['add_time'])." 22:00:00");
                     if($addtiem>=$check_time){
                         $orderolddata['best_time'] = strtotime(date('Y-m-d',$order['add_time'])." 22:00:00")+86400;
//                         自提订单配送时间逾期更改
//                         $orderolddata['best_time'] = strtotime(date('Y-m-d',$order['add_time'])." 22:30:00")+86400;
                         $orderolddata['best_time_start'] = strtotime(date('Y-m-d',$order['add_time'])." 10:00:00")+86400;
                     }else{
                         $orderolddata['best_time'] = strtotime(date('Y-m-d',$order['add_time'])." 22:00:00");
//                         $orderolddata['best_time'] = strtotime(date('Y-m-d',$order['add_time'])." 22:30:00");
                         $orderolddata['best_time_start'] = strtotime(date('Y-m-d',$order['add_time'])." 10:00:00");
                     }
                 }
                 $order_info_mod->where(array('order_id'=>$order['order_id']))->save($orderolddata);
                 $order_list[]= $order;
				 $this->goods_sell_notily($order);
                 return $order_list;
             }
         }else{
             $goods_amount=0;
             $i=0;//记录预售分单个数
             $order_goods_count=$order_goods_count-1;
             $orderbesttime=array();//根据预售商品发货时间进行分组
             $goods_mod= M('goods');
             $presell_flas='';//分单类型标识符前缀
             $act_ids=array();//相同活动ID，分组捆绑
             foreach ($order_goods as $ka=>$va ){
                 if($va['act_id']>0){
                     $act_ids[$va['act_id']][]=$va;
                 }
             }
             $del_addgoods=array();//删除已捆绑的商品
             foreach ($order_goods as $k=>$v){
                 if(in_array($v['rec_id'], $del_addgoods,true)){
                     continue;
                 }
                 if($v['is_presell']==1){
                     $presell_flas='is_presell_1';
                     $is_auto_morrow_presell=$goods_mod->where(array('goods_id'=>$v['goods_id']))->getField('is_auto_morrow_presell');
                     if($is_auto_morrow_presell==1){
                         $presell_flas='morrow_presell';
                     }
                     if($v['delivery_type']==1){//分段发货
                         $delivery_time=$this->check_shippingtime($v['goods_id'],$order['pay_time']);
                         if($delivery_time){
                             $new_data = date('Y-m-d',$delivery_time);
                             $delivery_time=strtotime($new_data." 22:00:00");
                             $start_time=strtotime($new_data." 10:00:00");
                             $v['best_time']=$delivery_time;
                             $v['best_time_start']=$start_time;
                             if($v['act_id']>0){
                                 if($act_ids[$v['act_id']]){
                                     foreach ($act_ids[$v['act_id']] as $kact=>$vact){
                                         $vact['best_time']=$v['best_time'];
                                         $vact['best_time_start']=$v['best_time_start'];
                                         $orderbesttime[$presell_flas.'_'.$v['best_time']][]=$vact;
                                         $del_addgoods[]=$vact['rec_id'];
                                     }
                                 }else{
                                     $orderbesttime[$presell_flas.'_'.$v['best_time']][]=$v;
                                 }
                             }else{
                                    $orderbesttime[$presell_flas.'_'.$v['best_time']][]=$v;
                             }
                         }else{
                             /*
                              * 默认为次日发货时间
                              * */
                             $pay_time=local_date('Y-m-d',$order['pay_time']);
                             $deliveryarr=$this->default_deliverytime($pay_time);
                             $v['best_time']=$deliveryarr['delivery_time'];
                             $v['best_time_start']=$deliveryarr['start_time'];
                             if($v['act_id']>0){
                                 if($act_ids[$v['act_id']]){
                                     foreach ($act_ids[$v['act_id']] as $kact=>$vact){
                                         $vact['best_time']=$v['best_time'];
                                         $vact['best_time_start']=$v['best_time_start'];
                                         $orderbesttime[$presell_flas.'_'.$v['best_time']][]=$vact;
                                         $del_addgoods[]=$vact['rec_id'];
                                     }
                                 }else{
                                     $orderbesttime[$presell_flas.'_'.$v['best_time']][]=$v;
                                 }
                             }else{
                                $orderbesttime[$presell_flas.'_'.$v['best_time']][]=$v;
                             } 
                         }
                     }elseif($v['delivery_type']==2){//定时方式
                         if($v['delivery_cycle']){
                             $pay_time=local_date('Y-m-d',$order['pay_time']);
                             $delivery_time = local_strtotime($pay_time.' +'.$v['delivery_cycle'].' day '.C('DEFAULT_PRESELL_TIME_H'));
                             if(empty($delivery_time)){
                                 /*
                                  * 默认为次日发货时间
                                  * */
                                 $pay_time=local_date('Y-m-d',$order['pay_time']);
                                 $deliveryarr=$this->default_deliverytime($pay_time);
                                 $v['best_time']=$deliveryarr['delivery_time'];
                                 $v['best_time_start']=$deliveryarr['start_time'];
                                 $v['include_presell']=$is_include_presell;
                                 if($v['act_id']>0){
                                     if($act_ids[$v['act_id']]){
                                         foreach ($act_ids[$v['act_id']] as $kact=>$vact){
                                             $vact['best_time']=$v['best_time'];
                                             $vact['best_time_start']=$v['best_time_start'];
                                             $vact['include_presell']=$v['include_presell'];
                                             $orderbesttime[$presell_flas.'_'.$v['best_time']][]=$vact;
                                             $del_addgoods[]=$vact['rec_id'];
                                         }
                                     }else{
                                         $orderbesttime[$presell_flas.'_'.$v['best_time']][]=$v;
                                     }
                                 }else{
                                    $orderbesttime[$presell_flas.'_'.$v['best_time']][]=$v;
                                 }
                             }
                             $new_data = date('Y-m-d',$delivery_time);
                             $delivery_time=strtotime($new_data." 22:00:00");
                             $start_time=strtotime($new_data." 10:00:00");
                             $v['best_time']=$delivery_time;
                             $v['best_time_start']=$start_time;
                             if($v['act_id']>0){
                                 if($act_ids[$v['act_id']]){
                                     foreach ($act_ids[$v['act_id']] as $kact=>$vact){
                                         $vact['best_time']=$v['best_time'];
                                         $vact['best_time_start']=$v['best_time_start'];
                                         $orderbesttime[$presell_flas.'_'.$v['best_time']][]=$vact;
                                         $del_addgoods[]=$vact['rec_id'];
                                     }
                                 }else{
                                     $orderbesttime[$presell_flas.'_'.$v['best_time']][]=$v;
                                 }
                             }else{
                                $orderbesttime[$presell_flas.'_'.$v['best_time']][]=$v;
                             }
                         }else{
                             /*
                              * 默认为次日发货时间
                              * */
                             $pay_time=local_date('Y-m-d',$order['pay_time']);
                             $best_time=date('Y-m-d',$order['best_time']);
                             if($v['delivery_cycle']==0 && $best_time===$pay_time){ // 当日达
                                $deliveryarr=$this->default_deliverytime($pay_time,0);
                             }else{
                                 $deliveryarr=$this->default_deliverytime($pay_time);
                             }
                             $v['best_time']=$deliveryarr['delivery_time'];
                             $v['best_time_start']=$deliveryarr['start_time'];
                             if($v['act_id']>0){
                                 if($act_ids[$v['act_id']]){
                                     foreach ($act_ids[$v['act_id']] as $kact=>$vact){
                                         $vact['best_time']=$v['best_time'];
                                         $vact['best_time_start']=$v['best_time_start'];
                                         $orderbesttime[$presell_flas.'_'.$v['best_time']][]=$vact;
                                         $del_addgoods[]=$vact['rec_id'];
                                     }
                                 }else{
                                     $orderbesttime[$presell_flas.'_'.$v['best_time']][]=$v;
                                 }
                             }else{
                                 $orderbesttime[$presell_flas.'_'.$v['best_time']][]=$v;
                             }
                         }
                     }else{
                         /*
                          * 默认为次日发货时间
                          * */
                         $pay_time=local_date('Y-m-d',$order['pay_time']);
                         $deliveryarr=$this->default_deliverytime($pay_time);
                         $v['best_time']=$deliveryarr['delivery_time'];
                         $v['best_time_start']=$deliveryarr['start_time'];
                         if($v['act_id']>0){
                               if($act_ids[$v['act_id']]){
                                     foreach ($act_ids[$v['act_id']] as $kact=>$vact){
                                         $vact['best_time']=$v['best_time'];
                                         $vact['best_time_start']=$v['best_time_start'];
                                         $orderbesttime[$presell_flas.'_'.$v['best_time']][]=$vact;
                                         $del_addgoods[]=$vact['rec_id'];
                                     }
                                 }else{
                                     $orderbesttime[$presell_flas.'_'.$v['best_time']][]=$v;
                                 }
                         }else{
                             $orderbesttime[$presell_flas.'_'.$v['best_time']][]=$v;
                         }
                     }
                 }else{
                     $presell_flas='is_presell_0';
                     $v['best_time']=$order['best_time'];
                     $v['best_time_start']=$order['best_time_start'];
                     if($v['act_id']>0){
                                if($act_ids[$v['act_id']]){
                                     foreach ($act_ids[$v['act_id']] as $kact=>$vact){
                                         $vact['best_time']=$v['best_time'];
                                         $vact['best_time_start']=$v['best_time_start'];
                                         $orderbesttime[$presell_flas.'_'.$v['best_time']][]=$vact;
                                         $del_addgoods[]=$vact['rec_id'];
                                     }
                                 }else{
                                     $orderbesttime[$presell_flas.'_'.$v['best_time']][]=$v;
                                 }
                     }else{
                         $orderbesttime[$presell_flas.'_'.$v['best_time']][]=$v;
                     }
                 }
             }
             unset($act_ids);
             unset($del_addgoods);
             $goods_amount_sum=0;
             $orderbesttime_count=count($orderbesttime);
             $i=1;
             foreach ($orderbesttime as $key=>$val){
                 $goods_amount=0;
                 $orderdata=$order;
                 unset($orderdata['order_id']);
                 $rec_id=array();
                 $best_time=0;
                 $flas=true;
                 $is_presell=0;
                 foreach ($val as $kk=>$vv){
                     $rec_id[]=$vv['rec_id'];
                     $amount=$vv['goods_price']*$vv['goods_number'];
                     $goods_amount=$goods_amount+$amount;
                     if($flas){
                         $best_time=$vv['best_time'];
                         $start_time=$vv['best_time_start'];
                         $flas=false;
                     }
                     if($vv['is_presell']==1 && $vv['buckle_inventory']==0){
                         $is_presell=1;
                     }
                 }
                 if($orderbesttime_count==1){
                     $orderolddata=array(
                         'batch_no'=>$batch_no,
                         'is_presell'=>$is_presell,
                         'best_time'=>$best_time,
                         'best_time_start'=>$start_time,
                     );
                     if($order['shipping_id']==2){
                         if($is_presell==1){
							 if($order['shipping_status']!=2) {
								 $orderolddata['shipping_status'] = 0;
							 }
                             //预售订单，自提时间显示最早发货日期-10:00-22:00
                             $orderolddata['best_time'] = strtotime(date('Y-m-d',$orderolddata['best_time'])." 22:00:00");
                             $orderolddata['best_time_start'] = strtotime(date('Y-m-d',$orderolddata['best_time_start'])." 10:00:00");
                         }else{
							 if($order['shipping_status']!=2) {
								 $orderolddata['shipping_status'] = 0;
							 }

                             //若现售订单，自提时间显示为下单日期-10:00-22:00
                             //若自提订单下单时间超过晚上9点半，则自提时间显示为 下单日期的次日 10:00-22:00
                             $addtiem = $order['add_time'];
                             $check_time = strtotime(date('Y-m-d',$order['add_time'])." 21:30:00");
                             if($addtiem>=$check_time){
                                 $orderolddata['best_time'] = strtotime(date('Y-m-d',$order['add_time'])." 22:00:00")+86400;
                                 $orderolddata['best_time_start'] = strtotime(date('Y-m-d',$order['add_time'])." 10:00:00")+86400;
                             }else{
                                 $orderolddata['best_time'] = strtotime(date('Y-m-d',$order['add_time'])." 22:00:00");
                                 $orderolddata['best_time_start'] = strtotime(date('Y-m-d',$order['add_time'])." 10:00:00");
                             }
                         }
                     }
                     if($is_presell==1){
                         $orderolddata['buckle_inventory']=0;
                     }
                     //修改原订单商品总价，支付总额
                     $order_info_mod->where(array('order_id'=>$order['order_id']))->save($orderolddata);
                     $order['best_time']=$orderolddata['best_time'];
                     $order['best_time_start']=$orderolddata['best_time_start'];
                     $order_list[]= $order;
					 $this->goods_sell_notily($order);
                     return $order_list;
                 }
                 if($orderbesttime_count==$i){
                     $orderolddata=array(
                         'goods_amount'=>$order['goods_amount']-$goods_amount_sum,
                         'batch_no'=>$batch_no,
                         'is_presell'=>$is_presell,
                         'best_time'=>$best_time,
                         'best_time_start'=>$start_time,
                     );
                      
                     if($order['shipping_id']==2){
                         if($is_presell==1){
							 if($order['shipping_status']!=2) {
								 $orderolddata['shipping_status'] = 0;
							 }
                             //预售订单，自提时间显示最早发货日期-10:00-22:00
                             $orderolddata['best_time'] = strtotime(date('Y-m-d',$orderolddata['best_time'])." 22:00:00");
                             $orderolddata['best_time_start'] = strtotime(date('Y-m-d',$orderolddata['best_time_start'])." 10:00:00");
                         }else{
							 if($order['shipping_status']!=2) {
								 $orderolddata['shipping_status'] = 0;
							 }

                             //若现售订单，自提时间显示为下单日期-10:00-22:00
                             //若自提订单下单时间超过晚上9点半，则自提时间显示为 下单日期的次日 10:00-22:00
                             $addtiem = $order['add_time'];
                             $check_time = strtotime(date('Y-m-d',$order['add_time'])." 21:30:00");
                             if($addtiem>=$check_time){
                                 $orderolddata['best_time'] = strtotime(date('Y-m-d',$order['add_time'])." 22:00:00")+86400;
                                 $orderolddata['best_time_start'] = strtotime(date('Y-m-d',$order['add_time'])." 10:00:00")+86400;
                             }else{
                                 $orderolddata['best_time'] = strtotime(date('Y-m-d',$order['add_time'])." 22:00:00");
                                 $orderolddata['best_time_start'] = strtotime(date('Y-m-d',$order['add_time'])." 10:00:00");
                             }
                         }
                         if(in_array($order['pay_id'],array(0,1,2))){
                             $orderolddata['order_amount']=$order['order_amount']-$goods_amount_sum+$order['bonus']+$order['discount'];
                         }elseif ($order['pay_id']==3){
                             $orderolddata['surplus']=$order['surplus']-$goods_amount_sum+$order['bonus']+$order['discount'];
                         }
                     }elseif ($order['shipping_id']==3){
                         if(in_array($order['pay_id'],array(1,2))){
                             $orderolddata['money_paid']=$order['money_paid']-$goods_amount_sum+$order['bonus']+$order['discount'];
                         }elseif ($order['pay_id']==3){
                             $orderolddata['surplus']=$order['surplus']-$goods_amount_sum+$order['bonus']+$order['discount'];
                         }
                     }
                     if($is_presell==1){
                         $orderolddata['buckle_inventory']=0;
                     }
                     //修改原订单商品总价，支付总额
                     $order_info_mod->where(array('order_id'=>$order['order_id']))->save($orderolddata);
                     $order['best_time']=$orderolddata['best_time'];
                     $order['best_time_start']=$orderolddata['best_time_start'];
                     $order_list[]= $order;
					 $this->goods_sell_notily($order);
                     return $order_list;
                 }
                 $orderdata['order_sn']=get_order_sn();
                 $orderdata['order_amount']=0;
                 $orderdata['surplus']=0;
                 $orderdata['money_paid']=0;
                 $orderdata['goods_amount']=$goods_amount;
                 $goods_amount_sum=$goods_amount_sum+$goods_amount;
                 $orderdata['best_time']=$best_time;
                 $orderdata['best_time_start']=$start_time;
                 if($orderdata['shipping_id']==2){
                     if($is_presell==1){
						 if($order['shipping_status']!=2) {
							 $orderolddata['shipping_status'] = 0;
						 }
                         //预售订单，自提时间显示最早发货日期-10:00-22:00
                         $orderolddata['best_time'] = strtotime(date('Y-m-d',$orderolddata['best_time'])." 22:00:00");
                         $orderolddata['best_time_start'] = strtotime(date('Y-m-d',$orderolddata['best_time_start'])." 10:00:00");
                     }else{
						 if($order['shipping_status']!=2) {
							 $orderolddata['shipping_status'] = 0;
						 }

                         //若现售订单，自提时间显示为下单日期-10:00-22:00
                         //若自提订单下单时间超过晚上9点半，则自提时间显示为 下单日期的次日 10:00-22:00
                         $addtiem = $order['add_time'];
                         $check_time = strtotime(date('Y-m-d',$order['add_time'])." 21:30:00");
                         if($addtiem>=$check_time){
                             $orderolddata['best_time'] = strtotime(date('Y-m-d',$order['add_time'])." 22:00:00")+86400;
                             $orderolddata['best_time_start'] = strtotime(date('Y-m-d',$order['add_time'])." 10:00:00")+86400;
                         }else{
                             $orderolddata['best_time'] = strtotime(date('Y-m-d',$order['add_time'])." 22:00:00");
                             $orderolddata['best_time_start'] = strtotime(date('Y-m-d',$order['add_time'])." 10:00:00");
                         }
                     }

                     if(in_array($orderdata['pay_id'],array(0,1,2))){
                         $orderdata['order_amount']=$goods_amount;
                     }elseif ($orderdata['pay_id']==3){
                         $orderdata['surplus']=$goods_amount;
                     }
                 }elseif ($orderdata['shipping_id']==3){
                     if(in_array($orderdata['pay_id'],array(1,2))){
                         $orderdata['money_paid']=$goods_amount;
                     }elseif ($orderdata['pay_id']==3){
                         $orderdata['surplus']=$goods_amount;
                     }
                 }
                 $orderdata['batch_no']=$batch_no;
                 $orderdata['is_presell']=$is_presell;
                 if($is_presell==1){
                     $orderdata['buckle_inventory']=0;
                 }
                 $order_id=$order_info_mod->add($orderdata);
                 if($order_id){
                     $rec_id=implode(',',$rec_id);
                     $order_goods_mod->where(array('rec_id'=>array('in',$rec_id)))->save(array('order_id'=>$order_id));
                     $orderdata['order_id'] = $order_id;
                     $order_list[] = $orderdata;
                 }
                 $i=$i+1;
             }
			 $this->goods_sell_notily($order);
			 unset($orderbesttime);
			 unset($order_goods);
             return $order_list;
         }
     }else{
	        $order_list[]= $order;
		 $this->goods_sell_notily($order);
	        return $order_list;
	}
}

	/*
	 * 将预售商品与常规商品分单
	 * */
public function split_single_old_1($order,$log_id){
	    $order_goods_mod=M('order_goods');
	    $order_goods=$order_goods_mod->alias('og')
	    ->field('og.rec_id,og.goods_id,og.goods_price,og.is_presell,og.buckle_inventory,og.goods_number,og.order_id,g.delivery_type,g.delivery_cycle')
	    ->join(C ( 'DB_PREFIX' ) .'goods as g on g.goods_id=og.goods_id')
	    ->where(array('og.order_id'=>$order['order_id']))
	    ->select();
	    $order_list = array();
	    if($order_goods){
	        //查询该笔订单商品存在现售商品数
	        //$isno_presellcount=$order_goods_mod->where(array('order_id'=>$order['order_id'],'is_presell'=>0))->count();
	        $order_info_mod=M('order_info');
	        $batch_no=$log_id;
	        $is_include_presell=0;// 0-未包含预售   1-包含预售
	        $order_goods_count=count($order_goods);//订单商品数
	        if($order_goods_count==1){
	            if($order_goods[0]['is_presell']==1){
	                $is_include_presell=1;
	                if($order_goods[0]['delivery_type']==1){//分段发货
	                    $delivery_time=$this->check_shippingtime($order_goods[0]['goods_id'],$order['pay_time']);
	                    if($delivery_time){
	                        $new_data = date('Y-m-d',$delivery_time);
	                        $delivery_time=strtotime($new_data." 20:30:00");
	                        $start_time=strtotime($new_data." 10:00:00");
	                    }else{
	                        /*
	                         * 默认为次日发货时间
	                         * */
	                        $pay_time=local_date('Y-m-d',$order['pay_time']);
	                        $deliveryarr=$this->default_deliverytime($pay_time);
	                        $delivery_time=$deliveryarr['delivery_time'];
	                        $start_time=$deliveryarr['start_time'];
	                    }
	                }elseif($order_goods[0]['delivery_type']==2){//定时方式
	                    if($order_goods[0]['delivery_cycle']){
	                        $pay_time=local_date('Y-m-d',$order['pay_time']);
	                        $delivery_time = local_strtotime($pay_time.' +'.$order_goods[0]['delivery_cycle'].' day '.C('DEFAULT_PRESELL_TIME_H'));
	                        if(empty($delivery_time)){

	                            /*
    	                         * 默认为次日发货时间
    	                         * */
    	                        $pay_time=local_date('Y-m-d',$order['pay_time']);
    	                        $deliveryarr=$this->default_deliverytime($pay_time);
    	                        $delivery_time=$deliveryarr['delivery_time'];
    	                        $start_time=$deliveryarr['start_time'];
	                        }else{
	                            $new_data = date('Y-m-d',$delivery_time);
	                            $delivery_time=strtotime($new_data." 20:30:00");
	                            $start_time=strtotime($new_data." 10:00:00");
	                        }
	                    }else{

	                        /*
	                         * 默认为次日发货时间
	                         * */
	                        $pay_time=local_date('Y-m-d',$order['pay_time']);
	                        $deliveryarr=$this->default_deliverytime($pay_time);
	                        $delivery_time=$deliveryarr['delivery_time'];
	                        $start_time=$deliveryarr['start_time'];
	                    }
	                }else{
	                    /*
	                         * 默认为次日发货时间
	                         * */
	                        $pay_time=local_date('Y-m-d',$order['pay_time']);
	                        $deliveryarr=$this->default_deliverytime($pay_time);
	                        $delivery_time=$deliveryarr['delivery_time'];
	                        $start_time=$deliveryarr['start_time'];
	                }
	                $orderolddata=array(
	                    'batch_no'=>$batch_no,
	                    'best_time_start'=>$start_time,
	                    'best_time'=>$delivery_time,
	                    'is_presell'=>$is_include_presell,
	                );
	                if($order['buckle_inventory']==1){
	                    if($order['shipping_id']==2){
							if($order['shipping_status']!=2) {
								$orderolddata['shipping_status'] = 0;
							}
	                    }
	                }else{
	                    if($order['shipping_id']==2){
							if($order['shipping_status']!=2) {
								$orderolddata['shipping_status'] = 0;
							}
	                    }
	                }
	                
	                $order_info_mod->where(array('order_id'=>$order['order_id']))->save($orderolddata);
	                $order['best_time'] = $orderolddata['best_time'];
	                $order['best_time_start'] = $orderolddata['best_time_start'];
	                $order_list[]= $order;
	                return $order_list;
	            }else{
	                $orderolddata=array(
	                    'is_presell'=>$is_include_presell,
	                );
	                if($order['shipping_id']==2){
						if($order['shipping_status']!=2) {
							$orderolddata['shipping_status'] = 0;
						}
	                }
	                $order_info_mod->where(array('order_id'=>$order['order_id']))->save($orderolddata);
	                $order_list[]= $order;
	                return $order_list;
	            }
	        }else{
	            $goods_amount=0;
	            $i=0;//记录预售分单个数
	            $order_goods_count=$order_goods_count-1;
	            $orderbesttime=array();//根据预售商品发货时间进行分组
	            foreach ($order_goods as $k=>$v){ 
	                if($v['is_presell']==1){
	                    if($v['delivery_type']==1){//分段发货
	                        $delivery_time=$this->check_shippingtime($v['goods_id'],$order['pay_time']);
	                        if($delivery_time){
	                            $new_data = date('Y-m-d',$delivery_time);
	                            $delivery_time=strtotime($new_data." 20:30:00");
	                            $start_time=strtotime($new_data." 10:00:00");
	                            $v['best_time']=$delivery_time;
	                            $v['best_time_start']=$start_time;
	                            $orderbesttime[$v['best_time']][]=$v;
	                        }else{
	                            /*
	                             * 默认为次日发货时间
	                             * */
	                            $pay_time=local_date('Y-m-d',$order['pay_time']);
	                            $deliveryarr=$this->default_deliverytime($pay_time);
	                            $v['best_time']=$deliveryarr['delivery_time'];
	                            $v['best_time_start']=$deliveryarr['start_time'];
	                            $orderbesttime[$v['best_time']][]=$v;
	                            
	                        }
	                    }elseif($v['delivery_type']==2){//定时方式
	                        if($v['delivery_cycle']){
	                            $pay_time=local_date('Y-m-d',$order['pay_time']);
	                            $delivery_time = local_strtotime($pay_time.' +'.$v['delivery_cycle'].' day '.C('DEFAULT_PRESELL_TIME_H'));
	                            if(empty($delivery_time)){
    	                                /*
    	                             * 默认为次日发货时间
    	                             * */
    	                            $pay_time=local_date('Y-m-d',$order['pay_time']);
	                                $deliveryarr=$this->default_deliverytime($pay_time);
    	                            $v['best_time']=$deliveryarr['delivery_time'];
    	                            $v['best_time_start']=$deliveryarr['start_time'];
    	                            $v['include_presell']=$is_include_presell;
    	                            $orderbesttime[$v['best_time']][]=$v;
	                            }
	                            $new_data = date('Y-m-d',$delivery_time);
	                            $delivery_time=strtotime($new_data." 20:30:00");
	                            $start_time=strtotime($new_data." 10:00:00");
	                            $v['best_time']=$delivery_time;
	                            $v['best_time_start']=$start_time;
	                            $orderbesttime[$v['best_time']][]=$v;
	                        }else{
	                            /*
	                             * 默认为次日发货时间
	                             * */
	                            $pay_time=local_date('Y-m-d',$order['pay_time']);
	                            $deliveryarr=$this->default_deliverytime($pay_time);
	                            $v['best_time']=$deliveryarr['delivery_time'];
	                            $v['best_time_start']=$deliveryarr['start_time'];
	                            $orderbesttime[$v['best_time']][]=$v;
	                        }
	                    }else{
	                           /*
	                             * 默认为次日发货时间
	                             * */
	                            $pay_time=local_date('Y-m-d',$order['pay_time']);
	                            $deliveryarr=$this->default_deliverytime($pay_time);
	                            $v['best_time']=$deliveryarr['delivery_time'];
	                            $v['best_time_start']=$deliveryarr['start_time'];
	                            $orderbesttime[$v['best_time']][]=$v;
	                    }
	                }else{
	                    $v['best_time']=$order['best_time'];
	                    $v['best_time_start']=$order['best_time_start'];
	                    $orderbesttime[$v['best_time']][]=$v;
	                }
	            }
	                
	                $goods_amount_sum=0;
	                $orderbesttime_count=count($orderbesttime);
	                $i=1;
	                 foreach ($orderbesttime as $key=>$val){
	                     $goods_amount=0;
	                    $orderdata=$order;
	                    unset($orderdata['order_id']);
	                    $rec_id=array();
	                    $best_time=0;
	                    $flas=true;
	                    $is_presell=0;
	                    foreach ($val as $kk=>$vv){
	                            $rec_id[]=$vv['rec_id'];
	                            $amount=$vv['goods_price']*$vv['goods_number'];
	                            $goods_amount=$goods_amount+$amount;
	                            if($flas){
	                                $best_time=$vv['best_time'];
	                                $start_time=$vv['best_time_start'];
	                                $flas=false;
	                            }
	                            if($vv['is_presell']==1 && $vv['buckle_inventory']==0){
	                                $is_presell=1;
	                            }
	                    }
	                    if($orderbesttime_count==1){
	                        $orderolddata=array(
	                            'batch_no'=>$batch_no,
	                            'is_presell'=>$is_presell,
	                            'best_time'=>$best_time,
	                            'best_time_start'=>$start_time,
	                        );
	                        if($order['shipping_id']==2){
	                            if($is_presell==1){
									if($order['shipping_status']!=2) {
										$orderolddata['shipping_status'] = 0;
									}
	                            }else{
									if($order['shipping_status']!=2) {
										$orderolddata['shipping_status'] = 0;
									}
	                            }
	                        }
	                        if($is_presell==1){
	                            $orderolddata['buckle_inventory']=0;
	                        }
	                        //修改原订单商品总价，支付总额
	                        $order_info_mod->where(array('order_id'=>$order['order_id']))->save($orderolddata);
	                        $order['best_time']=$orderolddata['best_time'];
	                        $order['best_time_start']=$orderolddata['best_time_start'];
	                        $order_list[]= $order;
	                        return $order_list;
	                    }
	                    if($orderbesttime_count==$i){
	                        $orderolddata=array(
	                            //'goods_amount'=>$order['goods_amount']-$goods_amount_sum+$order['bonus'],
	                            'goods_amount'=>$order['goods_amount']-$goods_amount_sum,
	                            'batch_no'=>$batch_no,
	                            'is_presell'=>$is_presell,
	                            'best_time'=>$best_time,
	                            'best_time_start'=>$start_time,
	                        );
	                        
	                        if($order['shipping_id']==2){
	                            if($is_presell==1){
									if($order['shipping_status']!=2) {
										$orderolddata['shipping_status'] = 0;
									}
	                            }else{
									if($order['shipping_status']!=2) {
										$orderolddata['shipping_status'] = 0;
									}
	                            }
	                            if(in_array($order['pay_id'],array(0,1,2))){
	                                $orderolddata['order_amount']=$order['order_amount']-$goods_amount_sum+$order['bonus'];
	                                //$orderolddata['order_amount']=$order['order_amount']-$goods_amount_sum;
	                            }elseif ($order['pay_id']==3){
	                                $orderolddata['surplus']=$order['surplus']-$goods_amount_sum+$order['bonus'];
	                                //$orderolddata['surplus']=$order['surplus']-$goods_amount_sum;
	                            }
	                        }elseif ($order['shipping_id']==3){
	                            if(in_array($order['pay_id'],array(1,2))){
	                                $orderolddata['money_paid']=$order['money_paid']-$goods_amount_sum+$order['bonus'];
	                               // $orderolddata['money_paid']=$order['money_paid']-$goods_amount_sum;
	                            }elseif ($order['pay_id']==3){
	                                $orderolddata['surplus']=$order['surplus']-$goods_amount_sum+$order['bonus'];
	                                //$orderolddata['surplus']=$order['surplus']-$goods_amount_sum;
	                            }
	                        }
	                        if($is_presell==1){
	                            $orderolddata['buckle_inventory']=0;
	                        }
	                        //修改原订单商品总价，支付总额
	                        $order_info_mod->where(array('order_id'=>$order['order_id']))->save($orderolddata);
	                        $order['best_time']=$orderolddata['best_time'];
	                        $order['best_time_start']=$orderolddata['best_time_start'];
	                        $order_list[]= $order;
	                        return $order_list;
	                    }
	                    $orderdata['order_sn']=get_order_sn();
	                    $orderdata['order_amount']=0;
	                    $orderdata['surplus']=0;
	                    $orderdata['money_paid']=0;
	                    $orderdata['goods_amount']=$goods_amount;
	                    $goods_amount_sum=$goods_amount_sum+$goods_amount;
	                    $orderdata['best_time']=$best_time;
	                    $orderdata['best_time_start']=$start_time;
	                    if($orderdata['shipping_id']==2){
	                        if($is_presell==1){
								if($order['shipping_status']!=2) {
									$orderdata['shipping_status'] = 0;
								}
	                        }else{
								if($order['shipping_status']!=2) {
									$orderdata['shipping_status'] = 0;
								}
	                        }
	                        if(in_array($orderdata['pay_id'],array(0,1,2))){
	                            $orderdata['order_amount']=$goods_amount;
	                        }elseif ($orderdata['pay_id']==3){
	                            $orderdata['surplus']=$goods_amount;
	                        }
	                    }elseif ($orderdata['shipping_id']==3){
	                        if(in_array($orderdata['pay_id'],array(1,2))){
	                            $orderdata['money_paid']=$goods_amount;
	                        }elseif ($orderdata['pay_id']==3){
	                            $orderdata['surplus']=$goods_amount;
	                        }
	                    }
	                    $orderdata['batch_no']=$batch_no;
	                    $orderdata['is_presell']=$is_presell;
	                    if($is_presell==1){
	                        $orderdata['buckle_inventory']=0;
	                    }
	                    $order_id=$order_info_mod->add($orderdata);
	                    if($order_id){
	                        $rec_id=implode(',',$rec_id);
	                        $order_goods_mod->where(array('rec_id'=>array('in',$rec_id)))->save(array('order_id'=>$order_id));
	                        $orderdata['order_id'] = $order_id;
	                        $order_list[] = $orderdata;
	                    }
	                    $i=$i+1;
	                }
	                return $order_list;
	        }
	    }else{
	        $order_list[]= $order;
	        return $order_list;
	    }
	}
	
	/*
	 * 将预售商品与常规商品分单
	 * */
	public function split_single_old($order,$log_id){
	    $this->goods_sell_notily($order);
	    
	    $order_goods_mod=M('order_goods');
	    $order_goods=$order_goods_mod->alias('og')
	    ->field('og.rec_id,og.goods_id,og.goods_price,og.is_presell,og.goods_number,og.order_id,g.delivery_type,g.delivery_cycle')
	    ->join(C ( 'DB_PREFIX' ) .'goods as g on g.goods_id=og.goods_id')
	    ->where(array('og.order_id'=>$order['order_id']))
	    ->select();
	    
	    $order_list = array();
	    if($order_goods){
	        //查询该笔订单商品存在现售商品数
	        $isno_presellcount=$order_goods_mod->where(array('order_id'=>$order['order_id'],'is_presell'=>0))->count();
	        $order_info_mod=M('order_info');
	        //$batch_no=$this->get_batch_no('OPC');//分单批次号
	        $batch_no=$log_id;
	        $order_goods_count=count($order_goods);//订单商品数
	        if($order_goods_count==1){
	            if($order_goods[0]['is_presell']==1){
	                if($order_goods[0]['delivery_type']==1){//分段发货
	                    $delivery_time=$this->check_shippingtime($order_goods[0]['goods_id'],$order['pay_time']);
	                    if($delivery_time){
	                        $new_data = date('Y-m-d',$delivery_time);
	                        $new_data = $new_data." 11:59:59";
	                        $delivery_time=strtotime($new_data);
	    
	    
	                    }else{
	                        $order_list[]= $order;
	                        return $order_list;
	                    }
	                }elseif($order_goods[0]['delivery_type']==2){//定时方式
	                    if($order_goods[0]['delivery_cycle']){
	                        $pay_time=local_date('Y-m-d',$order['pay_time']);
	                        $delivery_time = local_strtotime($pay_time.' +'.$order_goods[0]['delivery_cycle'].' day '.C('DEFAULT_PRESELL_TIME_H'));
	                        if(empty($delivery_time)){
	                            $order_list[]= $order;
	                            return $order_list;
	                        }else{
	                            $new_data = date('Y-m-d',$delivery_time);
	                            $new_data = $new_data." 11:59:59";
	                            $delivery_time=strtotime($new_data);
	                        }
	                    }else{
	                        $order_list[]= $order;
	                        return $order_list;
	                    }
	                }else{
	                    $order_list[]= $order;
	                    return $order_list;
	                }
	                $orderolddata=array(
	                    'batch_no'=>$batch_no,
	                    'best_time'=>$delivery_time
	                );
	                $order['best_time'] = $delivery_time;
	                $order_info_mod->where(array('order_id'=>$order['order_id']))->save($orderolddata);
	                $order_list[]= $order;
	                return $order_list;
	            }else{
	                $order_list[]= $order;
	                return $order_list;
	            }
	        }
	        $goods_amount=0;
	        $i=0;//记录预售分单个数
	        $order_goods_count=$order_goods_count-1;
	        foreach ($order_goods as $k=>$v){
	            if($v['is_presell']==1){
	                $orderdata=$order;
	                unset($orderdata['order_id']);
	                if($v['delivery_type']==1){//分段发货
	                    $delivery_time=$this->check_shippingtime($v['goods_id'],$order['pay_time']);
	                    if($delivery_time){
	                        $new_data = date('Y-m-d',$delivery_time);
	                        $new_data = $new_data." 11:59:59";
	                        $orderdata['best_time']=strtotime($new_data);
	                    }else{
	                        continue;
	                    }
	                }elseif($v['delivery_type']==2){//定时方式
	                    if($v['delivery_cycle']){
	                        $pay_time=local_date('Y-m-d',$order['pay_time']);
	                        $delivery_time = local_strtotime($pay_time.' +'.$v['delivery_cycle'].' day '.C('DEFAULT_PRESELL_TIME_H'));
	                        if(empty($delivery_time)){
	                            continue;
	                        }
	                        $new_data = date('Y-m-d',$delivery_time);
	                        $new_data = $new_data." 11:59:59";
	                        $orderdata['best_time']=strtotime($new_data);
	                    }else{
	                        continue;
	                    }
	                }else{
	                    continue;
	                }
	                $amount=$v['goods_price']*$v['goods_number'];
	                $orderdata['order_sn']=get_order_sn();
	                $orderdata['order_amount']=0;
	                $orderdata['surplus']=0;
	                $orderdata['money_paid']=0;
	                $orderdata['goods_amount']=$amount;
	                $goods_amount=$goods_amount+$amount;
	                if($isno_presellcount==0){ // 此订单商品全部为预售商品,保持最后一个预售商品为原始订单（不进行分单）
	                    if($order_goods_count==$i){
	                        $orderolddata=array(
	                            'goods_amount'=>$order['goods_amount']-$goods_amount+$amount,
	                            'batch_no'=>$batch_no,
	                            'is_presell'=>1,
	                            'best_time'=>$orderdata['best_time'],
	                        );
	                        if($order['shipping_id']==2){
	                            if(in_array($order['pay_id'],array(0,1,2))){
	                                $orderolddata['order_amount']=$order['order_amount']-$goods_amount+$amount;
	                            }elseif ($order['pay_id']==3){
	                                $orderolddata['surplus']=$order['surplus']-$goods_amount+$amount;
	                            }
	                        }elseif ($order['shipping_id']==3){
	                            if(in_array($order['pay_id'],array(1,2))){
	                                $orderolddata['money_paid']=$order['money_paid']-$goods_amount+$amount;
	                            }elseif ($order['pay_id']==3){
	                                $orderolddata['surplus']=$order['surplus']-$goods_amount+$amount;
	                            }
	                        }
	                        //修改原订单商品总价，支付总额
	                        $order_info_mod->where(array('order_id'=>$order['order_id']))->save($orderolddata);
	                        $order_list[]= $order;
	                        return $order_list;
	                    }
	                }
	                if($orderdata['shipping_id']==2){
	                    if(in_array($orderdata['pay_id'],array(0,1,2))){
	                        $orderdata['order_amount']=$amount;
	                    }elseif ($orderdata['pay_id']==3){
	                        $orderdata['surplus']=$amount;
	                    }
	                }elseif ($orderdata['shipping_id']==3){
	                    if(in_array($orderdata['pay_id'],array(1,2))){
	                        $orderdata['money_paid']=$amount;
	                    }elseif ($orderdata['pay_id']==3){
	                        $orderdata['surplus']=$amount;
	                    }
	                }
	                $orderdata['batch_no']=$batch_no;
	                $order_id=$order_info_mod->add($orderdata);
	                if($order_id){
	                    $order_goods_mod->where(array('order_id'=>$v['order_id'],'is_presell'=>1,'rec_id'=>$v['rec_id']))->save(array('order_id'=>$order_id));
	                    $order_list[] = $orderdata;
	                }
	                $i=$i+1;
	            }else{
	                continue;
	            }
	        }
	        $orderolddata=array(
	            'goods_amount'=>$order['goods_amount']-$goods_amount,
	            'batch_no'=>$batch_no,
	            'is_presell'=>0
	        );
	        if($order['shipping_id']==2){
	            if(in_array($order['pay_id'],array(0,1,2))){
	                $orderolddata['order_amount']=$order['order_amount']-$goods_amount;
	            }elseif ($order['pay_id']==3){
	                $orderolddata['surplus']=$order['surplus']-$goods_amount;
	            }
	        }elseif ($order['shipping_id']==3){
	            if(in_array($order['pay_id'],array(1,2))){
	                $orderolddata['money_paid']=$order['money_paid']-$goods_amount;
	            }elseif ($order['pay_id']==3){
	                $orderolddata['surplus']=$order['surplus']-$goods_amount;
	            }
	        }
	        //修改原订单商品总价，支付总额
	        $order_info_mod->where(array('order_id'=>$order['order_id']))->save($orderolddata);
	        $order_list[]= $order;
	        return $order_list;
	    }else{
	        return $order_list;
	    }
	}
	
	/*
	 * 检查该预售商品配送状态统计销售量
	 * */
    public function check_ordergoods_sales($goods_id,$best_time){
	        $count=$order_goods_mod=M('order_goods as og')->field('SUM(og.goods_number) as goods_num')->join(C('DB_PREFIX').'order_info as oi on og.order_id=oi.order_id')
	                        ->where('og.goods_id='.$goods_id.' and og.is_presell=1 and oi.shipping_status=0 and oi.pay_status=2')
	                        ->select();
	       if($count[0]['goods_num']>=0){
	           return $count[0]['goods_num'];
	       }else{
	           return 0;
	       }
	}
	
	/*
	 * 检查预售商品属于哪个发货时间
	 * */
	public function check_shippingtime($goods_id,$paytime){
	    $slesnum=$this->check_ordergoods_sales($goods_id,$paytime);
	    if(!$slesnum){
	        $slesnum=0;
	    }
	    $where=array('goods_id'=>$goods_id,'delivery_time'=>array('EGT',$paytime));
	    $where['_string']='endval>='.$slesnum.' or '.$slesnum.'=0';
	    $delivery_time=M('goods_presell_time')->where($where)->order('delivery_time asc')->getField('delivery_time');
	    if($delivery_time){
	        return $delivery_time;
	    }else{
	        return false;
	    }
	}
	
	public function get_ordergoods($orer_id, $is_presell=0){
		$data=array('og.order_id'=>$orer_id,'og.is_presell'=>$is_presell);
		if($is_presell==0){
			$data=array('og.order_id'=>$orer_id,'og.is_presell'=>$is_presell,'og.is_negative_to_sell'=>$is_presell);
		}
	    $order_goods=M('order_goods as og')
	    ->field('og.rec_id,og.goods_id,og.goods_sn,og.goods_name,og.goods_number,oi.order_sn')
	    ->join(C('DB_PREFIX').'order_info as oi on og.order_id=oi.order_id')
	    ->where($data)
	    ->select();

	    if($order_goods){
	        return $order_goods;
	    }else{
	        return false;
	    }
	}
	
	/*根据ID获取区域对应名称*/
	private  function get_region_name($id){
	    $res=M('region')->where(array('region_id'=>$id))->find();
	    return $res['region_name'];
	}
	
	
	/**
	 * 射线法计算坐标是否在规定图形内
	 * @param $polygon
	 * @param $longitude
	 * @param $latitude
	 * @return bool
	 */
	private function isPointInPolygon($polygon, $longitude, $latitude){
	    $count = count($polygon);
	    $px = $longitude;
	    $py = $latitude;
	    $flag = false;
	    for ($i = 0, $j = $count - 1; $i < $count; $j = $i, $i++) {
	        $sy = $polygon[$i]['lng'];
	        $sx = $polygon[$i]['lat'];
	        $ty = $polygon[$j]['lng'];
	        $tx = $polygon[$j]['lat'];
	        if ($px == $sx && $py == $sy || $px == $tx && $py == $ty)
	        {
	            return true;
	        }
	        if ($sy < $py && $ty >= $py || $sy >= $py && $ty < $py) {
	            $x = $sx + ($py - $sy) * ($tx - $sx) / ($ty - $sy);
	            if ($x == $px){
	                return true;
	            }
	            if ($x > $px){
	                $flag = !$flag;
	            }
	
	        }
	    }
	    return $flag;
	}
	
	/**
	 * 得到新订单号
	 * @return  string
	 */
	private function get_batch_no($prefix) {
	    /* 选择一个随机的方案 */
	    mt_srand((double) microtime() * 1000000);
	
	    return $prefix.date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
	}
	
	
	/**
	 * 获取商品详情
	 * @param $good_id
	 * @return mixed
     */
	public function get_good_info($good_id){
		return M("goods")->field("goods_id,goods_name,goods_sn")->where(array("goods_id"=>$good_id))->find();
	}


	public function upload_file(){
		$upload = new \Think\Upload();// 实例化上传类
		$upload->maxSize   =     3145728 ;// 设置附件上传大小
		$upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
		$upload->rootPath  =      './Uploads/'; // 设置附件上传根目录
		$upload->savePath  =      ''; // 设置附件上传（子）目录
		$info   =   $upload->upload();
		if(!$info) {// 上传错误提示错误信息
			//$this->error($upload->getError());
		}else{// 上传成功 获取上传文件信息
			$upload_dir = array();
			foreach($info as $key=>$file){
				$upload_dir[$key] = $upload->rootPath.$file['savepath'].$file['savename'];
			}
		}
	}



	/**
	 * 提交订单退货请求
	 * @param $order_id int
	 * @param $good_id array
	 * @param $good_num array
	 * @param $good_photo array
	 * @param $good_des array
     */
	public function submit_refund($order_id, $good_id, $good_num, $good_photo, $good_des){

		if(!is_numeric($order_id)) returnApiError("order id is null");


		$back_order_num = M("back_order")->where(array("order_id"=>$order_id))->count();
		if($back_order_num>0){
			returnApiError('sorry,this order is refund state');
		}



		$order_info = D('order_info');
		$sql = "SELECT COUNT(sdx_order_info.id) FROM sdx_order_info,sdx_order_action WHERE sdx_order_info.shipping_status = 2 
				AND sdx_order_info.order_id = sdx_order_action.order_id AND sdx_order_action.shipping_status = 2 AND 
				sdx_order_action.log_time>(".gmtime()."-86400)";

		$res = $order_info->execute($sql);

		if (!$res){
			returnApiError('order overtime or order status not complete state');
		}


		//查询发货单里面的订单信息

		$delivery_order = M("delivery_order")->where("order_id=".$order_id)->find();
		if ($delivery_order){

		//检查发货单里面的商品是否为适合的数量

			foreach ($good_id as $key=>$value){
				//
				if(is_numeric($value)){
					$goods_number = M("delivery_goods")->where("delivery_id = ".$delivery_order['delivery_id']." and goods_id=".$value)->getField("send_number");
					if($goods_number<$good_num[$key]){
						returnApiError("good id: ".$value.", refund num out of range");
					}

				}else{
					returnApiError("goods is in not int number");
				}
			}




			$data['delivery_sn'] = $delivery_order['delivery_sn'];
			$data['order_sn'] = $delivery_order['order_sn'];
			$data['order_id'] = $delivery_order['order_id'];
			$data['add_time'] = $delivery_order['add_time'];
			$data['shipping_id'] = $delivery_order['shipping_id'];
			$data['user_id'] = $delivery_order['user_id'];
			$data['action_user'] = 'buyer';	//dddd
			$data['consignee'] = $delivery_order['consignee'];
			$data['address'] = $delivery_order['address'];
			$data['Country'] = $delivery_order['country'];
			$data['province'] = $delivery_order['province'];
			$data['City'] = $delivery_order['city'];
			$data['district'] = $delivery_order['district'];
			$data['sign_building'] = $delivery_order['sign_building'];
			$data['Email'] = $delivery_order['email'];
			$data['Zipcode'] = $delivery_order['zipcode'];
			$data['Tel'] = $delivery_order['tel'];
			$data['Mobile'] = $delivery_order['mobile'];
			$data['best_time'] = $delivery_order['best_time'];
			$data['postscript'] = $delivery_order['postscript'];
			$data['how_oos'] = $delivery_order['how_oos'];
			$data['insure_fee'] = $delivery_order['insure_fee'];
			$data['shipping_fee'] = $delivery_order['shipping_fee'];
			$data['update_time'] = $delivery_order['update_time'];
			$data['suppliers_id'] = $delivery_order['suppliers_id'];
			$data['return_time'] = gmtime();
			$data['agency_id'] = $delivery_order['agency_id'];
			$data['invoice_no'] = $delivery_order['invoice_no'];
			$data['status'] = 1;


			$back_order_id = M("back_order")->add($data);

			if($back_order_id) {


				$good_photos = $this->upload_file();

				$refund_good = array();

				foreach ($good_id as $key=>$value){
					//
					if(is_numeric($value)){

						$refund_good[$key] = M("order_goods")->where("order_id =".$order_id." and goods_id=".$value)->find();
						$refund_good[$key]['refund_num'] = $good_num[$key];
						$refund_good[$key]['describe'] = $good_des[$key];
						$refund_good[$key]['good_photo'] = $good_photos[$key];
						$refund_good[$key]['back_id'] = $back_order_id;

						M("back_goods")->add($refund_good[$key]);

					}
				}

				returnApiSuccess(null,"success");
			}
		}
	}


	public function refund_state($order_id){
		$refund = M("back_action")->where(array("order_id"=>$order_id))->select();
		if ($refund){
			returnApiSuccess($refund);
		}else{
			returnApiError("no db");
		}
	}
	
	/*
	 * 根据仓库ID和商品ID查询该商品未发货的商品数量
	 * */
	public function get_no_delivergoods_order_number($wid=0,$goods_id){
	    $goods_num=$this->alias('oi')
	           ->field('SUM(og.goods_number) as goods_num')
	           ->join(C ( 'DB_PREFIX' ) .'order_goods as og on oi.order_id=og.order_id')
	           ->where('og.goods_id='.$goods_id.' and oi.wid='.$wid.' and oi.shipping_status='.SS_UNSHIPPED)
	           ->select();
	    if($goods_num[0]['goods_num']){
	        return $goods_num[0]['goods_num'];
	    }else{
	        return 0;
	    }       
	}


	/**
	 * 获取订单详情并发送邮件
	 * @param $order_id
	 * @return bool
     */
	public function goods_sell_notily($order){
		if(empty($order)) return false;
		//$order = M("order_info")->where("order_id = 129")->find();
        import('Vendor.smtp_new');
		$order_good = M("order_goods")->where(array("order_id"=>$order['order_id'],"is_presell"=>1))->field("goods_id,goods_number,goods_name,goods_sn")->select();

		foreach ($order_good as $goods){
			$goods_email = M("goods")->where(array("goods_id"=>$goods['goods_id']))->getField('email');

			if($goods_email){

				$data['order_id'] = $order['order_id'];
				$data['action_user'] = "SYSTEM";
				$data['order_status'] = $order['order_status'];
				$data['shipping_status'] = $order['shipping_status'];
				$data['pay_status'] = $order['pay_status'];
				$data['action_note'] = $goods['goods_name']."<br/>已发送邮件至:".$goods_email;
				$data['log_time'] = gmtime();
				M("order_action")->add($data);


				$smtpemailto = $goods_email;


				$mailbody = "
<table border='0' cellpadding='0' cellspacing='0' width='100%'>
<tbody><tr>
  <td bgcolor='#EFF2F7' align='center' style='padding:22px 0 36px 0;' class='padding5'>
  <table border='0' cellpadding='0' cellspacing='0' style='border-radius:4px; margin:0 auto; background-color:#ffffff' width='650' class='responsive-table'>
    <tbody>
    <tr>
      <td style='background-color:#ffffff; padding:0 50px 45px 50px;' class='padding1'>
        <table border='0' cellpadding='0' cellspacing='0' width='100%'>
           <tbody><tr>
             <td bgcolor='#ffffff' align='middle' style='background-color:#ffffff; font-size: 22px; color:#303C4B; font-weight:bold; padding:0 0 40px 0; line-height:32px;' colspan='2' class='padding4'>
               <span class='title' style='padding-bottom: 5px; border-bottom: 5px solid #ffd900;'>预售商品订单确认</span>
             </td>
          </tr>
          <tr>
             <td class='padding7' bgcolor='#ffffff' align='left' style='background-color:#ffffff; font-size: 15px; color:#4C5764; line-height:27px;' colspan='2'>
             购买者（uid）：".$order['user_id']."<br>
             订单号：".$order['order_sn']."<br>
             下单时间：".local_date('Y-m-d H:i:s', $order['add_time'])."<br>
             收货人：".$order['consignee']."<br>
             收货地址：".$order['address'].$order['sign_building']."<br>
             最佳送货时间：".date('Y-m-d H:i:s', $order['best_time_start'])." 至 ".date('Y-m-d H:i:s', $order['best_time'])."<br>
             订购商品：".$goods['goods_name']."(".$goods['goods_number'].")<br>
             订购数：".$goods['goods_number']."<br>
             为确保收到邮件，请将“admin@shidexian.com”加入白名单<br>
             </td>
          </tr>
        </tbody></table>
      </td>
    </tr>
        <tr>
      <td align='center' class='padding'>
        <table border='0' cellspacing='0' cellpadding='0' class='responsive-table'>
          <tbody><tr>
            <td>
              <span style='font-family:Hiragino Sans GB;font-size:16px;'>
              <a style='text-decoration:none;color:#ffffff;' href='##' target='_blank'>
               <div style='padding:10px 29px 10px 29px;border-radius:5px;text-align:center;text-decoration:none;background-color:#2bbdf8;color:#ffffff;font-size:20px;margin:0;white-space:nowrap'>食得鲜@广州优果蔬网络科技有限公司</div>
              </a>
              </span>
              <br>
            </td>
          </tr>
        </tbody></table>
      </td>
    </tr>
      </tbody></table>
    </td>
    </tr>
</tbody></table>
</td>
</tr>
</tbody></table>
                ";//邮件内容


                $mail = new \MySendMail();
                $mail->setServer("smtp.ym.163.com", "admin@shidexian.com", "sdxqwe123", 465, true); //到服务器的SSL连接;
                $mail->setFrom("admin@shidexian.com");

                $mail->setReceiver($goods_email);

//        $mail->setReceiver("XXX@qq.com");
                $mail->setCc("poptser@foxmail.com");
//        $mail->setCc("XXX@qq.com");
//        $mail->setBcc("XXX@qq.com");
//        $mail->setBcc("XXX@126.com");
                $mail->setMail("预售商品订单确认",$mailbody);
                $mail->sendMail();
			}
		}
	}

    /**
     * 获取当前22点之前未收货确认的自提单
     * Created by Jerry
     * @param $end_time
     * @return bool|mixed
     */
	public function get_pickup_order_by_time_for_shipping_id($end_time)
    {

        if (empty($end_time)) {
            return false;
        }

        $where = array(
            'add_time'          =>  array('LT', $end_time), //当天下单时间之前
//            'shipping_status'   =>  array('NEQ', SS_RECEIVED), //未收货
            'shipping_status'   =>  array('EQ', SS_SHIPPED), //已发货
            'order_status'      =>  array(
                array('EQ', OS_CONFIRMED), //已确认
                array('EQ', OS_SPLITED),    //已分单
                array('EQ', OS_SPLITING_PART),  //部分分单
//                array('NEQ', OS_INVALID),   //不查询无效订单
//                array('NEQ', OS_CANCELED),  //不查询取消订单
//                array('NEQ', OS_RETURNED),  //不查询退货订单
                'OR'
            ),
//            'order_status'      =>  array('EQ', OS_CONFIRMED), //已确认
            'pay_status'        =>  array('EQ', PS_PAYED),  //已付款
            'shipping_id'       =>  array('EQ', 2), //自提
        );

        $field = 'order_id, order_sn, user_id, consignee, shipping_status, best_time, best_time_start, mobile';

        return $this->field($field)->where($where)->order('add_time desc')->group('order_sn')->select();
    }


    /**
     * 修改自提单配送时间
     * Created by Jerry
     * @param $orderId
     * @param $updateData
     * @return bool
     */
    public function update_pickup_order_by_id($orderId, $updateData)
    {

        if (empty($orderId) || empty($updateData)) {
            return false;
        }

        $where = array(
            'order_id'  =>  $orderId
        );

        $result = $this->where($where)->save($updateData);

        if ($result !== false && is_numeric($result)) {
            return $result;
        }

        throw_exception($this->getError());
    }


	/**
	 * 获取当天促销价商品订单数
	 * Created by Jerry
	 * @param $user_id
	 * @param $goods_sn
	 * @return mixed
	 */
    public function get_order_promote_by_to_day_for_count($user_id, $goods_sn)
	{
		$time = date('Y-m-d H:i:s', gmtime());
//		$sql = "SELECT
//					COUNT(*) AS promote_count
//				FROM
//					sdx_order_info AS o,
//					sdx_order_goods AS og
//				WHERE
//					og.order_id = o.order_id
//						AND o.user_id = '{$user_id}'
//						AND o.order_status <> 2
//						AND og.giving = 4
//						AND og.goods_sn = '{$goods_sn}'
//						AND TO_DAYS(FROM_UNIXTIME(o.add_time, '%Y-%m-%d %H:%i:%S')) = TO_DAYS('{$time}')";

		$sql = "SELECT
					COUNT(og.rec_id) AS promote_count
				FROM
					sdx_order_info AS o
				LEFT JOIN sdx_order_goods AS og ON o.order_id = og.order_id 
				WHERE
				o.user_id = '{$user_id}'
				AND o.order_status <> 2
				AND o.order_status <> 3
				AND og.giving = 4
				AND og.goods_sn = '{$goods_sn}'
				AND TO_DAYS(FROM_UNIXTIME(o.add_time, '%Y-%m-%d %H:%i:%S')) = TO_DAYS('{$time}')";

		$data = $this->query($sql);

		return $data[0]['promote_count'];

	}

	/**
	 * 返回当天该秒杀商品订单总数
	 * Created by Jerry
	 * @param $user_id
	 * @param $goods_id
	 * @return mixed
	 */
	public function get_order_buy_now_by_to_day_for_count($user_id, $goods_id)
	{
		$time = date('Y-m-d H:i:s', gmtime());
		$sql = "SELECT 
					COUNT(*) AS buynow_count
				FROM
					sdx_order_info AS o,
					sdx_order_goods AS og
				WHERE
					og.order_id = o.order_id
						AND o.user_id = '{$user_id}'
						AND o.order_status <> 2
						AND og.giving = 5
						AND og.goods_id = '{$goods_id}'
						AND TO_DAYS(FROM_UNIXTIME(o.add_time, '%Y-%m-%d %H:%i:%S')) = TO_DAYS('{$time}')";

		$data = $this->query($sql);

		return $data[0]['buynow_count'];

	}


	/**
	 * 返回指定商品促销订单数量
	 * Created by Jerry
	 * @param $user_id
	 * @param $goods_sn
	 * @return mixed
	 */
	public function get_order_promote_by_number($user_id, $goods_sn, $start_time, $end_time)
	{
		$sql = "SELECT 
					COUNT(*) AS promote_count
				FROM
					sdx_order_info AS o,
					sdx_order_goods AS og
				WHERE
					og.order_id = o.order_id
						AND o.user_id = '{$user_id}'
						AND o.order_status <> 2
						AND og.giving = 4
						AND og.goods_sn = '{$goods_sn}'
								AND o.add_time >= '{$start_time}'
								AND o.add_time < '{$end_time}'";

		$data = $this->query($sql);
		return $data[0]['promote_count'];
	}


	/**
	 * 返回指定用户该秒杀时间内秒杀商品订单总数
	 * Created by Jerry
	 * @param $user_id
	 * @param $goods_id
	 * @param $start_time
	 * @param $end_time
	 * @return mixed
	 */
	public function get_order_buy_now_by_number($user_id, $goods_id, $start_time, $end_time)
	{
		$sql = "SELECT 
					COUNT(*) AS buynow_count
				FROM
					sdx_order_info AS o,
					sdx_order_goods AS og
				WHERE
					og.order_id = o.order_id
						AND o.user_id = '{$user_id}'
						AND o.order_status <> 2
						AND og.giving = 5
						AND og.goods_id = '{$goods_id}'
								AND o.add_time >= '{$start_time}'
								AND o.add_time < '{$end_time}'";

		$data = $this->query($sql);
		return $data[0]['buynow_count'];
	}

	/**
	 * 判断是否为新用户
	 * Created by Jerry
	 * @param int $userId
	 * @return bool
	 */
	public function isNewUser($userId = 0)
	{
		if (empty($userId)) {
			return false;
		}

		$where = array(
			'user_id'			=>	$userId,
			'shipping_status'	=>	SS_RECEIVED,
			'order_status'		=>	array('in', array(
				OS_CONFIRMED,
				OS_SPLITED,
			)),
		);

		$number = $this->field('order_id')->where($where)->count('order_id');

		$orderNumber = C('NEW_USER_ORDER_NUMBER');

		if ($number > $orderNumber) {
			return false;
		}

		return true;
	}

    /**
     * @author Jerry
     * @param int $userId
     * @param int $goodsId
     * @return mixed
     */
	public function isBuyGoodsByUserIdAndGoodsId($userId = 0, $goodsId = 0)
    {
        $where = array(
            'o.user_id'         =>  $userId,
            'og.goods_id'       =>  $goodsId,
            'o.shipping_status' =>  array(array('eq', 2), array('eq', 6), 'OR'),
        );

        $join = 'LEFT JOIN sdx_order_goods AS og ON o.order_id = og.order_id';

        $count = $this->alias('o')
                        ->join($join)
                        ->where($where)
                        ->count('o.order_id');

        return $count;
    }

    /**
     * 获取该会员已购买此商品总数
     * @author Jerry
     * @param int $userId
     * @param int $goodsId
     * @return mixed
     */
    public function findOrderGoodsSumByUserId($userId = 0, $goodsId = 0)
    {
        $time = date('Y-m-d H:i:s', gmtime());

        $where = array(
            'o.user_id'     =>  $userId,
            'og.giving'     =>  0,
            'og.goods_id'   =>  $goodsId,
            "TO_DAYS(FROM_UNIXTIME(o.add_time, '%Y-%m-%d %H:%i:%S')) = TO_DAYS('{$time}')"
        );

        $field = 'og.goods_number';

        $join = 'LEFT JOIN sdx_order_goods as og on o.order_id = og.order_id';
        $number = $this->alias('o')
                        ->field($field)
                        ->join($join)
                        ->where($where)
                        ->sum('og.goods_number');

        return $number;
    }

	public function get_wid_info($wid){
		$off_store_wid=C("gk_sender_info");
		return $off_store_wid[$wid];
	}

}